openadminjs 0.1.23 → 0.1.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/template/apps/admin/app/layout.tsx +2 -9
- package/template/apps/api/package.json +19 -20
- package/template/apps/api/src/app.module.test.ts +12 -0
- package/template/apps/api/src/app.module.ts +17 -11
- package/template/apps/api/src/common/openadmin-throttler.guard.ts +39 -0
- package/template/apps/api/src/common/request-logging.interceptor.test.ts +39 -0
- package/template/apps/api/src/common/request-logging.interceptor.ts +5 -3
- package/template/apps/api/src/graphql/admin-resources.args.ts +15 -0
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +20 -1
- package/template/apps/api/src/graphql/ensure-gql-paramtypes.ts +15 -0
- package/template/apps/api/src/graphql/graphql-schema.test.ts +8 -0
- package/template/apps/api/src/queue/queue.module.ts +1 -8
- package/template/apps/api/src/queue/queue.processor.ts +26 -6
- package/template/apps/api/src/queue/queue.service.test.ts +33 -0
- package/template/apps/api/src/queue/queue.service.ts +30 -12
- package/template/package.json +17 -0
- package/template/prisma/seed.ts +30 -1
package/package.json
CHANGED
|
@@ -1,17 +1,10 @@
|
|
|
1
1
|
import type { Metadata } from "next";
|
|
2
|
-
import { Inter } from "next/font/google";
|
|
3
2
|
import { ThemeProvider } from "next-themes";
|
|
4
3
|
import { ApiErrorBanner } from "../components/api-error-banner";
|
|
5
4
|
import { AuthGuard } from "../components/auth-guard";
|
|
6
5
|
import { BRAND } from "../lib/brand";
|
|
7
6
|
import "./globals.css";
|
|
8
7
|
|
|
9
|
-
const inter = Inter({
|
|
10
|
-
subsets: ["latin", "cyrillic"],
|
|
11
|
-
variable: "--font-inter",
|
|
12
|
-
display: "swap"
|
|
13
|
-
});
|
|
14
|
-
|
|
15
8
|
function resolveMetadataBase(): URL {
|
|
16
9
|
const origin = process.env.ADMIN_ORIGIN ?? "http://localhost:3000";
|
|
17
10
|
try {
|
|
@@ -47,8 +40,8 @@ export const metadata: Metadata = {
|
|
|
47
40
|
|
|
48
41
|
export default function RootLayout({ children }: { children: React.ReactNode }) {
|
|
49
42
|
return (
|
|
50
|
-
<html lang="en" suppressHydrationWarning
|
|
51
|
-
<body
|
|
43
|
+
<html lang="en" suppressHydrationWarning>
|
|
44
|
+
<body>
|
|
52
45
|
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
|
|
53
46
|
<AuthGuard>
|
|
54
47
|
<ApiErrorBanner />
|
|
@@ -15,22 +15,21 @@
|
|
|
15
15
|
"pretest": "pnpm run prisma:generate",
|
|
16
16
|
"test": "vitest run",
|
|
17
17
|
"db:migrate": "prisma migrate dev --schema ../../prisma/schema.prisma",
|
|
18
|
-
"db:seed": "
|
|
18
|
+
"db:seed": "tsx ../../prisma/seed.ts"
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@apollo/server": "
|
|
22
|
-
"@as-integrations/express5": "
|
|
21
|
+
"@apollo/server": "5.5.0",
|
|
22
|
+
"@as-integrations/express5": "1.1.2",
|
|
23
23
|
"@casl/ability": "^6.8.1",
|
|
24
|
-
"@nestjs/apollo": "
|
|
25
|
-
"@nestjs/
|
|
26
|
-
"@nestjs/
|
|
27
|
-
"@nestjs/
|
|
28
|
-
"@nestjs/
|
|
29
|
-
"@nestjs/
|
|
30
|
-
"@nestjs/
|
|
31
|
-
"@nestjs/
|
|
32
|
-
"@nestjs/
|
|
33
|
-
"@nestjs/throttler": "^6.5.0",
|
|
24
|
+
"@nestjs/apollo": "13.4.0",
|
|
25
|
+
"@nestjs/common": "11.1.21",
|
|
26
|
+
"@nestjs/config": "4.0.4",
|
|
27
|
+
"@nestjs/core": "11.1.21",
|
|
28
|
+
"@nestjs/graphql": "13.4.0",
|
|
29
|
+
"@nestjs/jwt": "11.0.2",
|
|
30
|
+
"@nestjs/platform-express": "11.1.21",
|
|
31
|
+
"@nestjs/swagger": "11.4.3",
|
|
32
|
+
"@nestjs/throttler": "6.5.0",
|
|
34
33
|
"@openadminjs/core": "workspace:*",
|
|
35
34
|
"@openadminjs/mail": "workspace:*",
|
|
36
35
|
"@openadminjs/payments": "workspace:*",
|
|
@@ -41,23 +40,23 @@
|
|
|
41
40
|
"@types/express": "^5.0.6",
|
|
42
41
|
"bcryptjs": "^2.4.3",
|
|
43
42
|
"bullmq": "^5.76.4",
|
|
44
|
-
"class-transformer": "
|
|
45
|
-
"class-validator": "
|
|
43
|
+
"class-transformer": "0.5.1",
|
|
44
|
+
"class-validator": "0.14.4",
|
|
46
45
|
"cookie-parser": "^1.4.7",
|
|
47
|
-
"graphql": "
|
|
48
|
-
"graphql-scalars": "
|
|
46
|
+
"graphql": "16.14.0",
|
|
47
|
+
"graphql-scalars": "1.25.0",
|
|
49
48
|
"helmet": "^8.0.0",
|
|
50
49
|
"ioredis": "^5.10.1",
|
|
51
50
|
"nodemailer": "^8.0.5",
|
|
52
|
-
"reflect-metadata": "
|
|
53
|
-
"rxjs": "
|
|
51
|
+
"reflect-metadata": "0.2.2",
|
|
52
|
+
"rxjs": "7.8.2",
|
|
54
53
|
"stripe": "^17.7.0",
|
|
55
54
|
"winston": "^3.19.0",
|
|
56
55
|
"winston-daily-rotate-file": "^5.0.0",
|
|
57
56
|
"zod": "^3.24.1"
|
|
58
57
|
},
|
|
59
58
|
"devDependencies": {
|
|
60
|
-
"@nestjs/cli": "
|
|
59
|
+
"@nestjs/cli": "11.0.21",
|
|
61
60
|
"@types/bcryptjs": "^2.4.6",
|
|
62
61
|
"@types/cookie-parser": "^1.4.10",
|
|
63
62
|
"@types/nodemailer": "^8.0.0",
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { throttleIpTracker } from "./app.module";
|
|
3
|
+
|
|
4
|
+
describe("app throttling", () => {
|
|
5
|
+
it("handles GraphQL requests without an HTTP request object", () => {
|
|
6
|
+
expect(throttleIpTracker(undefined)).toBe("unknown");
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
it("uses the request IP for HTTP requests", () => {
|
|
10
|
+
expect(throttleIpTracker({ ip: "127.0.0.1" })).toBe("127.0.0.1");
|
|
11
|
+
});
|
|
12
|
+
});
|
|
@@ -6,10 +6,11 @@ import { Module } from "@nestjs/common";
|
|
|
6
6
|
import { APP_GUARD, APP_INTERCEPTOR } from "@nestjs/core";
|
|
7
7
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
|
8
8
|
import { JwtService } from "@nestjs/jwt";
|
|
9
|
-
import {
|
|
9
|
+
import { ThrottlerModule } from "@nestjs/throttler";
|
|
10
10
|
import { PrismaService } from "./common/prisma.service";
|
|
11
11
|
import { LoggingModule } from "./common/logging.module";
|
|
12
12
|
import { RequestLoggingInterceptor } from "./common/request-logging.interceptor";
|
|
13
|
+
import { OpenAdminThrottlerGuard } from "./common/openadmin-throttler.guard";
|
|
13
14
|
import { AuthModule } from "./auth/auth.module";
|
|
14
15
|
import { AdminModule } from "./admin/admin.module";
|
|
15
16
|
import { GraphqlApiModule } from "./graphql/graphql.module";
|
|
@@ -23,6 +24,12 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
23
24
|
existsSync(p)
|
|
24
25
|
);
|
|
25
26
|
|
|
27
|
+
type ThrottleRequest = { headers?: { authorization?: string }; ip?: string } | undefined;
|
|
28
|
+
|
|
29
|
+
export function throttleIpTracker(req: ThrottleRequest): string {
|
|
30
|
+
return req?.ip ?? "unknown";
|
|
31
|
+
}
|
|
32
|
+
|
|
26
33
|
@Module({
|
|
27
34
|
imports: [
|
|
28
35
|
ConfigModule.forRoot({
|
|
@@ -39,14 +46,14 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
39
46
|
name: "default",
|
|
40
47
|
ttl: 60_000,
|
|
41
48
|
limit: 100,
|
|
42
|
-
getTracker:
|
|
49
|
+
getTracker: throttleIpTracker
|
|
43
50
|
},
|
|
44
51
|
{
|
|
45
52
|
name: "perUser",
|
|
46
53
|
ttl: 60_000,
|
|
47
54
|
limit: Number(config.get("RATE_LIMIT_USER_PER_MIN") ?? 120),
|
|
48
|
-
getTracker: async (req:
|
|
49
|
-
const h = req
|
|
55
|
+
getTracker: async (req: ThrottleRequest) => {
|
|
56
|
+
const h = req?.headers?.authorization;
|
|
50
57
|
const t = h?.startsWith("Bearer ") ? h.slice(7) : undefined;
|
|
51
58
|
if (t) {
|
|
52
59
|
try {
|
|
@@ -59,7 +66,7 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
59
66
|
/* use IP bucket for invalid JWT */
|
|
60
67
|
}
|
|
61
68
|
}
|
|
62
|
-
return `ip:${req
|
|
69
|
+
return `ip:${req?.ip ?? "anon"}`;
|
|
63
70
|
}
|
|
64
71
|
}
|
|
65
72
|
]
|
|
@@ -73,12 +80,11 @@ const envFilePath = [join(process.cwd(), ".env"), join(process.cwd(), "apps", "a
|
|
|
73
80
|
controllers: [HealthController],
|
|
74
81
|
providers: [
|
|
75
82
|
PrismaService,
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
{
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
}
|
|
83
|
+
RequestLoggingInterceptor,
|
|
84
|
+
PluginApiInterceptor,
|
|
85
|
+
{ provide: APP_GUARD, useClass: OpenAdminThrottlerGuard },
|
|
86
|
+
{ provide: APP_INTERCEPTOR, useExisting: RequestLoggingInterceptor },
|
|
87
|
+
{ provide: APP_INTERCEPTOR, useExisting: PluginApiInterceptor }
|
|
82
88
|
],
|
|
83
89
|
exports: [PrismaService]
|
|
84
90
|
})
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ExecutionContext, Injectable } from "@nestjs/common";
|
|
2
|
+
import { GqlExecutionContext } from "@nestjs/graphql";
|
|
3
|
+
import { ThrottlerGuard } from "@nestjs/throttler";
|
|
4
|
+
|
|
5
|
+
type HeaderWritable = Record<string, unknown> & {
|
|
6
|
+
header?: (name: string, value: string | number) => unknown;
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const noopResponse: HeaderWritable = {
|
|
10
|
+
header: () => undefined
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
function isHeaderWritable(input: unknown): input is HeaderWritable {
|
|
14
|
+
return Boolean(input && typeof input === "object" && "header" in input);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@Injectable()
|
|
18
|
+
export class OpenAdminThrottlerGuard extends ThrottlerGuard {
|
|
19
|
+
protected getRequestResponse(context: ExecutionContext): {
|
|
20
|
+
req: Record<string, unknown>;
|
|
21
|
+
res: HeaderWritable;
|
|
22
|
+
} {
|
|
23
|
+
if (context.getType<string>() === "graphql") {
|
|
24
|
+
const gqlContext = GqlExecutionContext.create(context).getContext<{
|
|
25
|
+
req?: Record<string, unknown>;
|
|
26
|
+
res?: unknown;
|
|
27
|
+
}>();
|
|
28
|
+
return {
|
|
29
|
+
req: gqlContext.req ?? {},
|
|
30
|
+
res: isHeaderWritable(gqlContext.res) ? gqlContext.res : noopResponse
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return super.getRequestResponse(context) as {
|
|
35
|
+
req: Record<string, unknown>;
|
|
36
|
+
res: HeaderWritable;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { CallHandler, ExecutionContext } from "@nestjs/common";
|
|
2
|
+
import { throwError } from "rxjs";
|
|
3
|
+
import { describe, expect, it, vi } from "vitest";
|
|
4
|
+
import { AppLoggerService } from "./app-logger.service";
|
|
5
|
+
import { RequestLoggingInterceptor } from "./request-logging.interceptor";
|
|
6
|
+
|
|
7
|
+
function httpContext(): ExecutionContext {
|
|
8
|
+
return {
|
|
9
|
+
getType: () => "http",
|
|
10
|
+
switchToHttp: () => ({
|
|
11
|
+
getRequest: () => ({ method: "POST", url: "/auth/login", ip: "127.0.0.1" }),
|
|
12
|
+
getResponse: () => ({ statusCode: 200 })
|
|
13
|
+
})
|
|
14
|
+
} as ExecutionContext;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe("RequestLoggingInterceptor", () => {
|
|
18
|
+
it("logs failed requests without throwing when the handler errors", async () => {
|
|
19
|
+
const logger = {
|
|
20
|
+
info: vi.fn(),
|
|
21
|
+
error: vi.fn()
|
|
22
|
+
} as unknown as AppLoggerService;
|
|
23
|
+
const interceptor = new RequestLoggingInterceptor(logger);
|
|
24
|
+
|
|
25
|
+
const handler: CallHandler = {
|
|
26
|
+
handle: () => throwError(() => new Error("db down"))
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
await expect(interceptor.intercept(httpContext(), handler).toPromise()).rejects.toThrow("db down");
|
|
30
|
+
expect(logger.error).toHaveBeenCalledWith(
|
|
31
|
+
"request.failed",
|
|
32
|
+
expect.objectContaining({
|
|
33
|
+
method: "POST",
|
|
34
|
+
path: "/auth/login",
|
|
35
|
+
errorMessage: "db down"
|
|
36
|
+
})
|
|
37
|
+
);
|
|
38
|
+
});
|
|
39
|
+
});
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CallHandler,
|
|
3
3
|
ExecutionContext,
|
|
4
|
+
Inject,
|
|
4
5
|
Injectable,
|
|
5
6
|
NestInterceptor
|
|
6
7
|
} from "@nestjs/common";
|
|
@@ -9,7 +10,7 @@ import { AppLoggerService } from "./app-logger.service";
|
|
|
9
10
|
|
|
10
11
|
@Injectable()
|
|
11
12
|
export class RequestLoggingInterceptor implements NestInterceptor {
|
|
12
|
-
constructor(private readonly logger: AppLoggerService) {}
|
|
13
|
+
constructor(@Inject(AppLoggerService) private readonly logger: AppLoggerService) {}
|
|
13
14
|
|
|
14
15
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
|
15
16
|
if (context.getType() !== "http") return next.handle();
|
|
@@ -25,11 +26,12 @@ export class RequestLoggingInterceptor implements NestInterceptor {
|
|
|
25
26
|
const path = req.url ?? "/";
|
|
26
27
|
const ip = req.ip ?? "";
|
|
27
28
|
const userId = req.user?.id;
|
|
29
|
+
const logger = this.logger;
|
|
28
30
|
|
|
29
31
|
return next.handle().pipe(
|
|
30
32
|
tap(() => {
|
|
31
33
|
const durationMs = Date.now() - started;
|
|
32
|
-
|
|
34
|
+
logger.info("request.completed", {
|
|
33
35
|
context: "http",
|
|
34
36
|
method,
|
|
35
37
|
path,
|
|
@@ -52,7 +54,7 @@ export class RequestLoggingInterceptor implements NestInterceptor {
|
|
|
52
54
|
? String((err as { message?: unknown }).message ?? "unknown error")
|
|
53
55
|
: "unknown error";
|
|
54
56
|
|
|
55
|
-
|
|
57
|
+
logger.error("request.failed", {
|
|
56
58
|
context: "http",
|
|
57
59
|
method,
|
|
58
60
|
path,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { ArgsType, Field, Int } from "@nestjs/graphql";
|
|
2
2
|
import { GraphQLJSON } from "graphql-scalars";
|
|
3
|
+
import { ensureGqlFieldTypes } from "./ensure-gql-paramtypes";
|
|
3
4
|
|
|
4
5
|
@ArgsType()
|
|
5
6
|
export class AdminResourceListArgs {
|
|
@@ -33,3 +34,17 @@ export class AdminResourceRecordArgs {
|
|
|
33
34
|
@Field(() => String)
|
|
34
35
|
id!: string;
|
|
35
36
|
}
|
|
37
|
+
|
|
38
|
+
ensureGqlFieldTypes(AdminResourceListArgs.prototype, {
|
|
39
|
+
name: String,
|
|
40
|
+
page: Number,
|
|
41
|
+
limit: Number,
|
|
42
|
+
search: String,
|
|
43
|
+
sort: String,
|
|
44
|
+
locale: String,
|
|
45
|
+
filter: GraphQLJSON
|
|
46
|
+
});
|
|
47
|
+
ensureGqlFieldTypes(AdminResourceRecordArgs.prototype, {
|
|
48
|
+
name: String,
|
|
49
|
+
id: String
|
|
50
|
+
});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "reflect-metadata";
|
|
2
2
|
import { describe, expect, it } from "vitest";
|
|
3
|
-
import { ensureGqlParamTypes } from "./ensure-gql-paramtypes";
|
|
3
|
+
import { ensureGqlFieldTypes, ensureGqlParamTypes } from "./ensure-gql-paramtypes";
|
|
4
4
|
|
|
5
5
|
describe("ensureGqlParamTypes", () => {
|
|
6
6
|
it("defines design:paramtypes when missing", () => {
|
|
@@ -22,4 +22,23 @@ describe("ensureGqlParamTypes", () => {
|
|
|
22
22
|
ensureGqlParamTypes(Sample.prototype, "handler", [String]);
|
|
23
23
|
expect(Reflect.getMetadata("design:paramtypes", Sample.prototype, "handler")).toEqual([Date]);
|
|
24
24
|
});
|
|
25
|
+
|
|
26
|
+
it("defines missing design:type metadata for GraphQL fields", () => {
|
|
27
|
+
class Sample {
|
|
28
|
+
name!: string;
|
|
29
|
+
count!: number;
|
|
30
|
+
}
|
|
31
|
+
ensureGqlFieldTypes(Sample.prototype, { name: String, count: Number });
|
|
32
|
+
expect(Reflect.getMetadata("design:type", Sample.prototype, "name")).toBe(String);
|
|
33
|
+
expect(Reflect.getMetadata("design:type", Sample.prototype, "count")).toBe(Number);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("does not overwrite existing field metadata", () => {
|
|
37
|
+
class Sample {
|
|
38
|
+
createdAt!: Date;
|
|
39
|
+
}
|
|
40
|
+
Reflect.defineMetadata("design:type", Date, Sample.prototype, "createdAt");
|
|
41
|
+
ensureGqlFieldTypes(Sample.prototype, { createdAt: String });
|
|
42
|
+
expect(Reflect.getMetadata("design:type", Sample.prototype, "createdAt")).toBe(Date);
|
|
43
|
+
});
|
|
25
44
|
});
|
|
@@ -13,3 +13,18 @@ export function ensureGqlParamTypes(
|
|
|
13
13
|
if (Array.isArray(existing) && existing.length >= paramTypes.length) return;
|
|
14
14
|
Reflect.defineMetadata(key, paramTypes, prototype, methodName);
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* `@Field(() => Type)` is still resolved through lazy metadata that expects
|
|
19
|
+
* `design:type` to exist. Define the property metadata when `tsx watch` did not emit it.
|
|
20
|
+
*/
|
|
21
|
+
export function ensureGqlFieldTypes(
|
|
22
|
+
prototype: object,
|
|
23
|
+
fieldTypes: Record<string, unknown>
|
|
24
|
+
): void {
|
|
25
|
+
const key = "design:type";
|
|
26
|
+
for (const [fieldName, fieldType] of Object.entries(fieldTypes)) {
|
|
27
|
+
if (Reflect.hasMetadata(key, prototype, fieldName)) continue;
|
|
28
|
+
Reflect.defineMetadata(key, fieldType, prototype, fieldName);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -4,6 +4,13 @@ import { AdminResourceListArgs, AdminResourceRecordArgs } from "./admin-resource
|
|
|
4
4
|
import { AdminResourcesResolver } from "./admin-resources.resolver";
|
|
5
5
|
|
|
6
6
|
describe("GraphQL schema (admin resources)", () => {
|
|
7
|
+
it("exposes design:type metadata for args fields when the compiler does not emit it", () => {
|
|
8
|
+
expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "name")).toBe(String);
|
|
9
|
+
expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "page")).toBe(Number);
|
|
10
|
+
expect(Reflect.getMetadata("design:type", AdminResourceListArgs.prototype, "filter")).toBeTruthy();
|
|
11
|
+
expect(Reflect.getMetadata("design:type", AdminResourceRecordArgs.prototype, "id")).toBe(String);
|
|
12
|
+
});
|
|
13
|
+
|
|
7
14
|
it("exposes design:paramtypes for Nest GraphQL when the compiler does not emit it", () => {
|
|
8
15
|
expect(
|
|
9
16
|
Reflect.getMetadata("design:paramtypes", AdminResourcesResolver.prototype, "adminResourceList")
|
|
@@ -15,4 +22,5 @@ describe("GraphQL schema (admin resources)", () => {
|
|
|
15
22
|
Reflect.getMetadata("design:paramtypes", AdminResourcesResolver.prototype, "adminRegisteredResourceNames")
|
|
16
23
|
).toEqual([Object]);
|
|
17
24
|
});
|
|
25
|
+
|
|
18
26
|
});
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Module } from "@nestjs/common";
|
|
2
2
|
import { JwtModule } from "@nestjs/jwt";
|
|
3
|
-
import { BullModule } from "@nestjs/bullmq";
|
|
4
3
|
import { PrismaService } from "../common/prisma.service";
|
|
5
4
|
import { AuthGuard } from "../common/auth.guard";
|
|
6
5
|
import { PermissionsGuard } from "../common/permissions.guard";
|
|
@@ -10,13 +9,7 @@ import { QueueService } from "./queue.service";
|
|
|
10
9
|
import { QueueProcessor } from "./queue.processor";
|
|
11
10
|
|
|
12
11
|
@Module({
|
|
13
|
-
imports: [
|
|
14
|
-
JwtModule.register({}),
|
|
15
|
-
BullModule.forRoot({
|
|
16
|
-
connection: { url: process.env.REDIS_URL ?? "redis://127.0.0.1:6379" }
|
|
17
|
-
}),
|
|
18
|
-
BullModule.registerQueue({ name: "default" })
|
|
19
|
-
],
|
|
12
|
+
imports: [JwtModule.register({})],
|
|
20
13
|
controllers: [QueueController],
|
|
21
14
|
providers: [QueueService, QueueProcessor, PrismaService, AuthGuard, PermissionsGuard, CaslAbilityFactory]
|
|
22
15
|
})
|
|
@@ -1,14 +1,34 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import type { Job } from "bullmq";
|
|
1
|
+
import { Inject, Injectable, Logger, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
|
|
2
|
+
import { Worker } from "bullmq";
|
|
3
|
+
import type { ConnectionOptions, Job } from "bullmq";
|
|
4
4
|
import { PrismaService } from "../common/prisma.service";
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
const QUEUE_NAME = "default";
|
|
7
|
+
|
|
8
|
+
function redisConnection(): ConnectionOptions | undefined {
|
|
9
|
+
const url = process.env.REDIS_URL?.trim();
|
|
10
|
+
return url ? { url } : undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
@Injectable()
|
|
14
|
+
export class QueueProcessor implements OnModuleInit, OnModuleDestroy {
|
|
8
15
|
private readonly logger = new Logger(QueueProcessor.name);
|
|
16
|
+
private worker?: Worker<{ initiatedBy?: string; at?: string }, { ok: boolean }>;
|
|
9
17
|
|
|
10
18
|
constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {
|
|
11
|
-
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
onModuleInit() {
|
|
22
|
+
const connection = redisConnection();
|
|
23
|
+
if (!connection) {
|
|
24
|
+
this.logger.log("Redis is not configured; queue worker is disabled.");
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
this.worker = new Worker(QUEUE_NAME, (job) => this.process(job), { connection });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async onModuleDestroy() {
|
|
31
|
+
await this.worker?.close();
|
|
12
32
|
}
|
|
13
33
|
|
|
14
34
|
async process(job: Job<{ initiatedBy?: string; at?: string }>) {
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { ServiceUnavailableException } from "@nestjs/common";
|
|
2
|
+
import { afterEach, describe, expect, it } from "vitest";
|
|
3
|
+
import { QueueService } from "./queue.service";
|
|
4
|
+
|
|
5
|
+
const originalRedisUrl = process.env.REDIS_URL;
|
|
6
|
+
|
|
7
|
+
describe("QueueService", () => {
|
|
8
|
+
afterEach(() => {
|
|
9
|
+
process.env.REDIS_URL = originalRedisUrl;
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it("degrades gracefully when Redis is not configured", async () => {
|
|
13
|
+
delete process.env.REDIS_URL;
|
|
14
|
+
const recent = [{ id: "job_1", name: "maintenance.sync", status: "completed" }];
|
|
15
|
+
const service = new QueueService({
|
|
16
|
+
jobLog: {
|
|
17
|
+
findMany: async () => recent
|
|
18
|
+
}
|
|
19
|
+
} as never);
|
|
20
|
+
|
|
21
|
+
await expect(service.getStats()).resolves.toEqual({
|
|
22
|
+
counts: {
|
|
23
|
+
active: 0,
|
|
24
|
+
waiting: 0,
|
|
25
|
+
completed: 0,
|
|
26
|
+
failed: 0,
|
|
27
|
+
delayed: 0
|
|
28
|
+
},
|
|
29
|
+
recent
|
|
30
|
+
});
|
|
31
|
+
await expect(service.dispatch("user_1")).rejects.toBeInstanceOf(ServiceUnavailableException);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
@@ -1,18 +1,35 @@
|
|
|
1
|
-
import { Inject, Injectable, ServiceUnavailableException } from "@nestjs/common";
|
|
2
|
-
import { InjectQueue } from "@nestjs/bullmq";
|
|
1
|
+
import { Inject, Injectable, OnModuleDestroy, ServiceUnavailableException } from "@nestjs/common";
|
|
3
2
|
import { Queue } from "bullmq";
|
|
3
|
+
import type { ConnectionOptions } from "bullmq";
|
|
4
4
|
import { PrismaService } from "../common/prisma.service";
|
|
5
5
|
|
|
6
|
+
const QUEUE_NAME = "default";
|
|
7
|
+
|
|
8
|
+
function redisConnection(): ConnectionOptions | undefined {
|
|
9
|
+
const url = process.env.REDIS_URL?.trim();
|
|
10
|
+
return url ? { url } : undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
6
13
|
@Injectable()
|
|
7
|
-
export class QueueService {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
) {}
|
|
14
|
+
export class QueueService implements OnModuleDestroy {
|
|
15
|
+
private readonly connection = redisConnection();
|
|
16
|
+
private readonly queue = this.connection ? new Queue(QUEUE_NAME, { connection: this.connection }) : undefined;
|
|
17
|
+
|
|
18
|
+
constructor(@Inject(PrismaService) private readonly prisma: PrismaService) {}
|
|
19
|
+
|
|
20
|
+
async onModuleDestroy() {
|
|
21
|
+
await this.queue?.close();
|
|
22
|
+
}
|
|
12
23
|
|
|
13
24
|
async getStats() {
|
|
14
25
|
const [counts, recent] = await Promise.all([
|
|
15
|
-
this.queue
|
|
26
|
+
this.queue?.getJobCounts("active", "waiting", "completed", "failed", "delayed") ?? {
|
|
27
|
+
active: 0,
|
|
28
|
+
waiting: 0,
|
|
29
|
+
completed: 0,
|
|
30
|
+
failed: 0,
|
|
31
|
+
delayed: 0
|
|
32
|
+
},
|
|
16
33
|
this.prisma.jobLog.findMany({ orderBy: { createdAt: "desc" }, take: 10 })
|
|
17
34
|
]);
|
|
18
35
|
|
|
@@ -20,9 +37,9 @@ export class QueueService {
|
|
|
20
37
|
}
|
|
21
38
|
|
|
22
39
|
async dispatch(userId: string) {
|
|
23
|
-
this.ensureRedisConfigured();
|
|
40
|
+
const queue = this.ensureRedisConfigured();
|
|
24
41
|
const payload = { initiatedBy: userId, at: new Date().toISOString() };
|
|
25
|
-
const job = await
|
|
42
|
+
const job = await queue.add("maintenance.sync", payload, {
|
|
26
43
|
removeOnComplete: 100,
|
|
27
44
|
attempts: 3,
|
|
28
45
|
backoff: { type: "exponential", delay: 1000 }
|
|
@@ -39,12 +56,13 @@ export class QueueService {
|
|
|
39
56
|
return { id: job.id, name: job.name };
|
|
40
57
|
}
|
|
41
58
|
|
|
42
|
-
private ensureRedisConfigured() {
|
|
43
|
-
if (!
|
|
59
|
+
private ensureRedisConfigured(): Queue {
|
|
60
|
+
if (!this.queue) {
|
|
44
61
|
throw new ServiceUnavailableException({
|
|
45
62
|
message: "Redis is not configured. Set REDIS_URL to enable queues.",
|
|
46
63
|
code: "REDIS_NOT_CONFIGURED"
|
|
47
64
|
});
|
|
48
65
|
}
|
|
66
|
+
return this.queue;
|
|
49
67
|
}
|
|
50
68
|
}
|
package/template/package.json
CHANGED
|
@@ -22,5 +22,22 @@
|
|
|
22
22
|
"tsx": "^4.19.2",
|
|
23
23
|
"typescript": "^5.7.2",
|
|
24
24
|
"vitest": "^3.2.0"
|
|
25
|
+
},
|
|
26
|
+
"pnpm": {
|
|
27
|
+
"overrides": {
|
|
28
|
+
"@nestjs/apollo": "13.4.0",
|
|
29
|
+
"@nestjs/common": "11.1.21",
|
|
30
|
+
"@nestjs/config": "4.0.4",
|
|
31
|
+
"@nestjs/core": "11.1.21",
|
|
32
|
+
"@nestjs/graphql": "13.4.0",
|
|
33
|
+
"@nestjs/jwt": "11.0.2",
|
|
34
|
+
"@nestjs/platform-express": "11.1.21",
|
|
35
|
+
"@nestjs/swagger": "11.4.3",
|
|
36
|
+
"@nestjs/throttler": "6.5.0",
|
|
37
|
+
"class-transformer": "0.5.1",
|
|
38
|
+
"class-validator": "0.14.4",
|
|
39
|
+
"reflect-metadata": "0.2.2",
|
|
40
|
+
"rxjs": "7.8.2"
|
|
41
|
+
}
|
|
25
42
|
}
|
|
26
43
|
}
|
package/template/prisma/seed.ts
CHANGED
|
@@ -1,11 +1,37 @@
|
|
|
1
1
|
import { PrismaClient } from "@prisma/client";
|
|
2
2
|
import bcrypt from "bcryptjs";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
3
5
|
import { createInterface } from "node:readline/promises";
|
|
4
6
|
import { stdin as input, stdout as output } from "node:process";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
5
8
|
import { materializeAllRoles, roleMatrixKey } from "@openadminjs/permissions";
|
|
6
9
|
import { catalogSlugList, permissionCatalog, roleBlueprints } from "../apps/api/src/access/catalog";
|
|
7
10
|
import { publicPermissionCatalog, publicRoleBlueprints } from "../apps/api/src/access/public-catalog";
|
|
8
11
|
|
|
12
|
+
function loadApiEnv(): void {
|
|
13
|
+
const rootDir = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
14
|
+
const candidates = [
|
|
15
|
+
join(process.cwd(), ".env"),
|
|
16
|
+
join(process.cwd(), "apps", "api", ".env"),
|
|
17
|
+
join(rootDir, "apps", "api", ".env")
|
|
18
|
+
];
|
|
19
|
+
const envFile = candidates.find((path) => existsSync(path));
|
|
20
|
+
if (!envFile) return;
|
|
21
|
+
|
|
22
|
+
for (const line of readFileSync(envFile, "utf8").split(/\r?\n/)) {
|
|
23
|
+
if (!line || line.trimStart().startsWith("#")) continue;
|
|
24
|
+
const separator = line.indexOf("=");
|
|
25
|
+
if (separator <= 0) continue;
|
|
26
|
+
const key = line.slice(0, separator).trim();
|
|
27
|
+
if (process.env[key] !== undefined) continue;
|
|
28
|
+
const value = line.slice(separator + 1).trim().replace(/^(['"])(.*)\1$/, "$2");
|
|
29
|
+
process.env[key] = value;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
loadApiEnv();
|
|
34
|
+
|
|
9
35
|
const prisma = new PrismaClient();
|
|
10
36
|
|
|
11
37
|
type SeedCredentials = {
|
|
@@ -118,7 +144,10 @@ async function main() {
|
|
|
118
144
|
|
|
119
145
|
const user = await prisma.user.upsert({
|
|
120
146
|
where: { email: superadmin.email },
|
|
121
|
-
update: {
|
|
147
|
+
update: {
|
|
148
|
+
name: "Admin",
|
|
149
|
+
passwordHash: await bcrypt.hash(superadmin.password, 12)
|
|
150
|
+
},
|
|
122
151
|
create: {
|
|
123
152
|
email: superadmin.email,
|
|
124
153
|
name: "Admin",
|