openadminjs 0.1.23 → 0.2.0

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.
Files changed (67) hide show
  1. package/README.md +97 -16
  2. package/dist/adapt-package-manager.d.ts +3 -0
  3. package/dist/adapt-package-manager.js +115 -0
  4. package/dist/adapt-package-manager.test.d.ts +1 -0
  5. package/dist/adapt-package-manager.test.js +76 -0
  6. package/dist/cli.e2e.test.d.ts +1 -0
  7. package/dist/cli.e2e.test.js +87 -0
  8. package/dist/create-project.d.ts +31 -2
  9. package/dist/create-project.js +296 -102
  10. package/dist/create-project.test.js +180 -4
  11. package/dist/database-providers.integration.test.d.ts +1 -0
  12. package/dist/database-providers.integration.test.js +64 -0
  13. package/dist/db-commands.d.ts +20 -0
  14. package/dist/db-commands.js +75 -0
  15. package/dist/db-commands.test.d.ts +1 -0
  16. package/dist/db-commands.test.js +27 -0
  17. package/dist/detect-package-manager.d.ts +8 -0
  18. package/dist/detect-package-manager.js +37 -0
  19. package/dist/doctor.d.ts +13 -0
  20. package/dist/doctor.js +203 -0
  21. package/dist/doctor.test.d.ts +1 -0
  22. package/dist/doctor.test.js +102 -0
  23. package/dist/index.d.ts +2 -1
  24. package/dist/index.js +233 -141
  25. package/dist/index.test.js +7 -3
  26. package/dist/render-schema.d.ts +20 -0
  27. package/dist/render-schema.js +37 -0
  28. package/dist/render-schema.test.d.ts +1 -0
  29. package/dist/render-schema.test.js +57 -0
  30. package/dist/secrets.d.ts +24 -0
  31. package/dist/secrets.js +93 -0
  32. package/dist/secrets.test.d.ts +1 -0
  33. package/dist/secrets.test.js +36 -0
  34. package/dist/security.d.ts +13 -0
  35. package/dist/security.js +168 -0
  36. package/dist/security.test.d.ts +1 -0
  37. package/dist/security.test.js +54 -0
  38. package/dist/validate-name.d.ts +33 -0
  39. package/dist/validate-name.js +206 -0
  40. package/dist/validate-name.test.d.ts +1 -0
  41. package/dist/validate-name.test.js +63 -0
  42. package/package.json +26 -1
  43. package/template/README.md +22 -3
  44. package/template/apps/admin/app/layout.tsx +2 -9
  45. package/template/apps/api/package.json +22 -20
  46. package/template/apps/api/src/app.module.test.ts +12 -0
  47. package/template/apps/api/src/app.module.ts +17 -11
  48. package/template/apps/api/src/common/json-field-codec.test.ts +76 -0
  49. package/template/apps/api/src/common/json-field-codec.ts +139 -0
  50. package/template/apps/api/src/common/openadmin-throttler.guard.ts +39 -0
  51. package/template/apps/api/src/common/prisma.service.test.ts +19 -0
  52. package/template/apps/api/src/common/prisma.service.ts +13 -0
  53. package/template/apps/api/src/common/request-logging.interceptor.test.ts +39 -0
  54. package/template/apps/api/src/common/request-logging.interceptor.ts +5 -3
  55. package/template/apps/api/src/graphql/admin-resources.args.ts +15 -0
  56. package/template/apps/api/src/graphql/ensure-gql-paramtypes.test.ts +20 -1
  57. package/template/apps/api/src/graphql/ensure-gql-paramtypes.ts +15 -0
  58. package/template/apps/api/src/graphql/graphql-apollo-config.test.ts +26 -0
  59. package/template/apps/api/src/graphql/graphql-schema.test.ts +8 -0
  60. package/template/apps/api/src/graphql/graphql.module.ts +13 -1
  61. package/template/apps/api/src/queue/queue.module.ts +1 -8
  62. package/template/apps/api/src/queue/queue.processor.ts +26 -6
  63. package/template/apps/api/src/queue/queue.service.test.ts +33 -0
  64. package/template/apps/api/src/queue/queue.service.ts +30 -12
  65. package/template/package.json +19 -0
  66. package/template/prisma/migrations/20260713120000_add_user_oidc_key_and_category_order/migration.sql +11 -0
  67. package/template/prisma/seed.ts +30 -1
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "openadminjs",
3
- "version": "0.1.23",
3
+ "version": "0.2.0",
4
+ "description": "CLI scaffold generator for OpenAdminJS monorepos (NestJS, Prisma, Next.js). Not a runtime library — use npx openadminjs create.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "openadminjs",
8
+ "admin",
9
+ "nestjs",
10
+ "nextjs",
11
+ "prisma",
12
+ "cli",
13
+ "scaffold",
14
+ "generator",
15
+ "monorepo"
16
+ ],
17
+ "homepage": "https://js-senpai.github.io/open-admin-js/",
18
+ "bugs": {
19
+ "url": "https://github.com/js-senpai/open-admin-js/issues"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/js-senpai/open-admin-js.git",
24
+ "directory": "packages/cli"
25
+ },
4
26
  "type": "module",
5
27
  "bin": {
6
28
  "openadminjs": "dist/index.js"
@@ -20,6 +42,9 @@
20
42
  "publishConfig": {
21
43
  "access": "public"
22
44
  },
45
+ "engines": {
46
+ "node": ">=20"
47
+ },
23
48
  "files": [
24
49
  "dist",
25
50
  "template",
@@ -1,17 +1,20 @@
1
1
  # __APP_NAME__
2
2
 
3
- Generated by [OpenAdminJS](https://openadminjs.dev).
3
+ Generated by [OpenAdminJS](https://js-senpai.github.io/open-admin-js/).
4
4
 
5
5
  ## Stack
6
6
 
7
- - **API** — Nest.js 10 + Prisma 6 (port 4000)
7
+ - **API** — Nest.js 11 + Prisma 6 (port 4000)
8
8
  - **Admin** — Next.js 15 back-office (port 3000)
9
9
  - **Web** — Next.js 15 public site (port 3001)
10
+ - **Database** — PostgreSQL, MySQL, or SQLite (chosen during `openadminjs create`)
10
11
 
11
12
  ## Getting started
12
13
 
13
14
  ```bash
14
15
  pnpm install
16
+ pnpm db:migrate # required on first run (especially for MySQL/SQLite)
17
+ pnpm db:seed
15
18
  pnpm dev
16
19
  ```
17
20
 
@@ -19,14 +22,30 @@ Admin panel → http://localhost:3000
19
22
  API + Swagger → http://localhost:4000/api/docs
20
23
  Public site → http://localhost:3001
21
24
 
25
+ Sign in with the superadmin email and password from the scaffold wizard (stored in `apps/api/.env`).
26
+
27
+ ## Environment
28
+
29
+ Real secrets live in **`apps/api/.env`** only. A tracked **`.env.example`** at the repo root documents the required keys. Never commit `.env` files.
30
+
31
+ | Provider | Typical `DATABASE_URL` |
32
+ | --- | --- |
33
+ | PostgreSQL | `postgresql://USER:PASSWORD@localhost:5432/db?schema=public` |
34
+ | MySQL | `mysql://USER:PASSWORD@localhost:3306/db` |
35
+ | SQLite | `file:./dev.db` |
36
+
37
+ On **SQLite**, `Json` columns are stored as `String` in the database; the API transparently JSON-encodes/decodes them at runtime.
38
+
22
39
  ## Useful commands
23
40
 
24
41
  | Command | Description |
25
42
  |---|---|
26
43
  | `pnpm dev` | Start API + admin in parallel |
27
- | `pnpm db:migrate` | Run Prisma migrations |
44
+ | `pnpm db:migrate` | Run Prisma migrations (`migrate dev`) |
28
45
  | `pnpm db:seed` | Seed database (creates superadmin) |
29
46
  | `pnpm db:studio` | Open Prisma Studio |
30
47
  | `pnpm build` | Build all workspaces |
31
48
  | `pnpm test` | Run all tests |
32
49
  | `pnpm lint` | Type-check all workspaces |
50
+ | `openadminjs doctor` | Check project health |
51
+ | `openadminjs security check` | Audit secrets and configuration |
@@ -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 className={inter.variable}>
51
- <body className={inter.className}>
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,24 @@
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": "prisma db seed --schema ../../prisma/schema.prisma"
18
+ "db:migrate:deploy": "prisma migrate deploy --schema ../../prisma/schema.prisma",
19
+ "db:studio": "prisma studio --schema ../../prisma/schema.prisma",
20
+ "db:reset": "prisma migrate reset --schema ../../prisma/schema.prisma",
21
+ "db:seed": "tsx ../../prisma/seed.ts"
19
22
  },
20
23
  "dependencies": {
21
- "@apollo/server": "^5.5.0",
22
- "@as-integrations/express5": "^1.1.2",
24
+ "@apollo/server": "5.5.0",
25
+ "@as-integrations/express5": "1.1.2",
23
26
  "@casl/ability": "^6.8.1",
24
- "@nestjs/apollo": "^13.4.0",
25
- "@nestjs/bullmq": "^11.0.4",
26
- "@nestjs/common": "^11.1.19",
27
- "@nestjs/config": "^4.0.4",
28
- "@nestjs/core": "^11.1.19",
29
- "@nestjs/graphql": "^13.4.0",
30
- "@nestjs/jwt": "^11.0.2",
31
- "@nestjs/platform-express": "^11.1.19",
32
- "@nestjs/swagger": "^11.4.2",
33
- "@nestjs/throttler": "^6.5.0",
27
+ "@nestjs/apollo": "13.4.0",
28
+ "@nestjs/common": "11.1.21",
29
+ "@nestjs/config": "4.0.4",
30
+ "@nestjs/core": "11.1.21",
31
+ "@nestjs/graphql": "13.4.0",
32
+ "@nestjs/jwt": "11.0.2",
33
+ "@nestjs/platform-express": "11.1.21",
34
+ "@nestjs/swagger": "11.4.3",
35
+ "@nestjs/throttler": "6.5.0",
34
36
  "@openadminjs/core": "workspace:*",
35
37
  "@openadminjs/mail": "workspace:*",
36
38
  "@openadminjs/payments": "workspace:*",
@@ -41,23 +43,23 @@
41
43
  "@types/express": "^5.0.6",
42
44
  "bcryptjs": "^2.4.3",
43
45
  "bullmq": "^5.76.4",
44
- "class-transformer": "^0.5.1",
45
- "class-validator": "^0.14.1",
46
+ "class-transformer": "0.5.1",
47
+ "class-validator": "0.14.4",
46
48
  "cookie-parser": "^1.4.7",
47
- "graphql": "^16.11.0",
48
- "graphql-scalars": "^1.25.0",
49
+ "graphql": "16.14.0",
50
+ "graphql-scalars": "1.25.0",
49
51
  "helmet": "^8.0.0",
50
52
  "ioredis": "^5.10.1",
51
53
  "nodemailer": "^8.0.5",
52
- "reflect-metadata": "^0.2.2",
53
- "rxjs": "^7.8.1",
54
+ "reflect-metadata": "0.2.2",
55
+ "rxjs": "7.8.2",
54
56
  "stripe": "^17.7.0",
55
57
  "winston": "^3.19.0",
56
58
  "winston-daily-rotate-file": "^5.0.0",
57
59
  "zod": "^3.24.1"
58
60
  },
59
61
  "devDependencies": {
60
- "@nestjs/cli": "^11.0.21",
62
+ "@nestjs/cli": "11.0.21",
61
63
  "@types/bcryptjs": "^2.4.6",
62
64
  "@types/cookie-parser": "^1.4.10",
63
65
  "@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 { ThrottlerGuard, ThrottlerModule } from "@nestjs/throttler";
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: (req: { ip?: string }) => req.ip ?? "unknown"
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: { headers?: { authorization?: string }; ip?: string }) => {
49
- const h = req.headers?.authorization;
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.ip ?? "anon"}`;
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
- { provide: APP_GUARD, useClass: ThrottlerGuard },
77
- { provide: APP_INTERCEPTOR, useClass: RequestLoggingInterceptor },
78
- {
79
- provide: APP_INTERCEPTOR,
80
- useClass: PluginApiInterceptor
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,76 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import {
3
+ decodeReadResult,
4
+ encodeWriteArgs,
5
+ isSqliteDatabaseUrl,
6
+ SQLITE_JSON_FIELDS
7
+ } from "./json-field-codec";
8
+
9
+ describe("isSqliteDatabaseUrl", () => {
10
+ it("detects file: URLs", () => {
11
+ expect(isSqliteDatabaseUrl("file:./dev.db")).toBe(true);
12
+ expect(isSqliteDatabaseUrl("FILE:./data/app.sqlite")).toBe(true);
13
+ expect(isSqliteDatabaseUrl("postgresql://localhost/db")).toBe(false);
14
+ expect(isSqliteDatabaseUrl("mysql://localhost/db")).toBe(false);
15
+ });
16
+ });
17
+
18
+ describe("encodeWriteArgs / decodeReadResult", () => {
19
+ it("round-trips Json-like fields for AuditLog", () => {
20
+ const payload = { title: "Hello", count: 2 };
21
+ const encoded = encodeWriteArgs("AuditLog", {
22
+ data: { action: "update", before: payload, after: { ...payload, count: 3 } }
23
+ });
24
+ expect(encoded.data).toMatchObject({
25
+ action: "update",
26
+ before: JSON.stringify(payload),
27
+ after: JSON.stringify({ ...payload, count: 3 })
28
+ });
29
+
30
+ const decoded = decodeReadResult("AuditLog", {
31
+ id: "1",
32
+ action: "update",
33
+ before: JSON.stringify(payload),
34
+ after: JSON.stringify({ ...payload, count: 3 })
35
+ }) as Record<string, unknown>;
36
+ expect(decoded.before).toEqual(payload);
37
+ expect(decoded.after).toEqual({ ...payload, count: 3 });
38
+ });
39
+
40
+ it("round-trips scopes array for ApiToken", () => {
41
+ const scopes = ["posts.read", "users.read"];
42
+ const encoded = encodeWriteArgs("ApiToken", { data: { name: "t", scopes } });
43
+ expect((encoded.data as Record<string, unknown>).scopes).toBe(JSON.stringify(scopes));
44
+
45
+ const decoded = decodeReadResult("ApiToken", {
46
+ id: "1",
47
+ name: "t",
48
+ scopes: JSON.stringify(scopes)
49
+ }) as Record<string, unknown>;
50
+ expect(decoded.scopes).toEqual(scopes);
51
+ });
52
+
53
+ it("leaves non-codec models unchanged", () => {
54
+ const data = { email: "a@b.dev", passwordHash: "x" };
55
+ expect(encodeWriteArgs("User", { data }).data).toEqual(data);
56
+ expect(decodeReadResult("User", data)).toEqual(data);
57
+ });
58
+
59
+ it("covers every model listed in SQLITE_JSON_FIELDS", () => {
60
+ expect(Object.keys(SQLITE_JSON_FIELDS).length).toBeGreaterThan(0);
61
+ for (const [model, fields] of Object.entries(SQLITE_JSON_FIELDS)) {
62
+ const sample = Object.fromEntries(fields.map((f) => [f, { k: f }]));
63
+ const encoded = encodeWriteArgs(model, { data: sample });
64
+ for (const field of fields) {
65
+ expect(typeof (encoded.data as Record<string, unknown>)[field]).toBe("string");
66
+ }
67
+ const decoded = decodeReadResult(model, {
68
+ id: "x",
69
+ ...Object.fromEntries(fields.map((f) => [f, JSON.stringify({ k: f })]))
70
+ }) as Record<string, unknown>;
71
+ for (const field of fields) {
72
+ expect(decoded[field]).toEqual({ k: field });
73
+ }
74
+ }
75
+ });
76
+ });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * SQLite has no native Json type. The CLI rewrites Json / scalar-list columns to
3
+ * String when scaffolding for SQLite. This module JSON-encodes those columns on
4
+ * write and JSON-decodes them on read so the rest of the API keeps working with
5
+ * objects/arrays as on PostgreSQL/MySQL.
6
+ *
7
+ * On PostgreSQL and MySQL this module is a no-op (isSqliteDatabaseUrl is false).
8
+ */
9
+
10
+ /** Prisma model name → fields stored as JSON text on SQLite. */
11
+ export const SQLITE_JSON_FIELDS: Readonly<Record<string, readonly string[]>> = {
12
+ AuditLog: ["before", "after"],
13
+ Setting: ["value"],
14
+ ApiToken: ["scopes"],
15
+ JobLog: ["payload"],
16
+ Product: ["metadata"],
17
+ Order: ["metadata"],
18
+ Transaction: ["metadata"],
19
+ WebhookLog: ["payload"],
20
+ AiMessage: ["meta"],
21
+ AiArtifact: ["meta"]
22
+ };
23
+
24
+ export function isSqliteDatabaseUrl(url: string | undefined): boolean {
25
+ return (url ?? "").trim().toLowerCase().startsWith("file:");
26
+ }
27
+
28
+ function jsonFieldsForModel(model: string): readonly string[] {
29
+ return SQLITE_JSON_FIELDS[model] ?? [];
30
+ }
31
+
32
+ function encodeValue(value: unknown): unknown {
33
+ if (value === null || value === undefined) return value;
34
+ if (typeof value === "string") return value;
35
+ return JSON.stringify(value);
36
+ }
37
+
38
+ function decodeValue(value: unknown): unknown {
39
+ if (value === null || value === undefined) return value;
40
+ if (typeof value !== "string") return value;
41
+ try {
42
+ return JSON.parse(value) as unknown;
43
+ } catch {
44
+ return value;
45
+ }
46
+ }
47
+
48
+ function encodeData(model: string, data: unknown): unknown {
49
+ if (!data || typeof data !== "object" || Array.isArray(data)) return data;
50
+ const fields = jsonFieldsForModel(model);
51
+ if (!fields.length) return data;
52
+ const copy = { ...(data as Record<string, unknown>) };
53
+ for (const field of fields) {
54
+ if (field in copy) copy[field] = encodeValue(copy[field]);
55
+ }
56
+ return copy;
57
+ }
58
+
59
+ function decodeRecord(model: string, record: unknown): unknown {
60
+ if (!record || typeof record !== "object" || Array.isArray(record)) return record;
61
+ const fields = jsonFieldsForModel(model);
62
+ if (!fields.length) return record;
63
+ const copy = { ...(record as Record<string, unknown>) };
64
+ for (const field of fields) {
65
+ if (field in copy) copy[field] = decodeValue(copy[field]);
66
+ }
67
+ return copy;
68
+ }
69
+
70
+ function decodeMany(model: string, records: unknown): unknown {
71
+ if (!Array.isArray(records)) return records;
72
+ return records.map((r) => decodeRecord(model, r));
73
+ }
74
+
75
+ type QueryArgs = { data?: unknown; create?: unknown; update?: unknown };
76
+
77
+ /** Encodes JSON fields inside Prisma write args (`data`, `create`, `update`). */
78
+ export function encodeWriteArgs(model: string, args: QueryArgs): QueryArgs {
79
+ const next = { ...args };
80
+ if (next.data !== undefined) next.data = encodeData(model, next.data);
81
+ if (next.create !== undefined) next.create = encodeData(model, next.create);
82
+ if (next.update !== undefined) next.update = encodeData(model, next.update);
83
+ return next;
84
+ }
85
+
86
+ export function decodeReadResult(model: string, result: unknown): unknown {
87
+ if (Array.isArray(result)) return decodeMany(model, result);
88
+ return decodeRecord(model, result);
89
+ }
90
+
91
+ type PrismaQueryHook = {
92
+ args: QueryArgs;
93
+ query: (args: QueryArgs) => Promise<unknown>;
94
+ };
95
+
96
+ /** Prisma Client extension — only applied when DATABASE_URL is a SQLite file URL. */
97
+ export function sqliteJsonCodecExtension() {
98
+ const queryConfig: Record<string, Record<string, (ctx: PrismaQueryHook) => Promise<unknown>>> = {};
99
+
100
+ for (const model of Object.keys(SQLITE_JSON_FIELDS)) {
101
+ queryConfig[model] = {
102
+ async create({ args, query }) {
103
+ const result = await query(encodeWriteArgs(model, args));
104
+ return decodeRecord(model, result);
105
+ },
106
+ async createMany({ args, query }) {
107
+ if (args.data && Array.isArray(args.data)) {
108
+ return query({ ...args, data: args.data.map((row) => encodeData(model, row)) });
109
+ }
110
+ return query(args);
111
+ },
112
+ async update({ args, query }) {
113
+ const result = await query(encodeWriteArgs(model, args));
114
+ return decodeRecord(model, result);
115
+ },
116
+ async updateMany({ args, query }) {
117
+ return query(encodeWriteArgs(model, args));
118
+ },
119
+ async upsert({ args, query }) {
120
+ const result = await query(encodeWriteArgs(model, args));
121
+ return decodeRecord(model, result);
122
+ },
123
+ async findUnique({ args, query }) {
124
+ const result = await query(args);
125
+ return decodeRecord(model, result);
126
+ },
127
+ async findFirst({ args, query }) {
128
+ const result = await query(args);
129
+ return decodeRecord(model, result);
130
+ },
131
+ async findMany({ args, query }) {
132
+ const result = await query(args);
133
+ return decodeMany(model, result);
134
+ }
135
+ };
136
+ }
137
+
138
+ return { name: "sqliteJsonCodec", query: queryConfig };
139
+ }
@@ -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,19 @@
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+ import { isSqliteDatabaseUrl } from "./json-field-codec";
3
+
4
+ describe("PrismaService SQLite wiring", () => {
5
+ const original = process.env.DATABASE_URL;
6
+
7
+ afterEach(() => {
8
+ if (original === undefined) delete process.env.DATABASE_URL;
9
+ else process.env.DATABASE_URL = original;
10
+ });
11
+
12
+ it("detects SQLite from DATABASE_URL (used by PrismaService constructor)", () => {
13
+ process.env.DATABASE_URL = "file:./dev.db";
14
+ expect(isSqliteDatabaseUrl(process.env.DATABASE_URL)).toBe(true);
15
+
16
+ process.env.DATABASE_URL = "postgresql://localhost/db";
17
+ expect(isSqliteDatabaseUrl(process.env.DATABASE_URL)).toBe(false);
18
+ });
19
+ });
@@ -1,8 +1,21 @@
1
1
  import { Injectable, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
2
2
  import { PrismaClient } from "@prisma/client";
3
+ import { isSqliteDatabaseUrl, sqliteJsonCodecExtension } from "./json-field-codec";
3
4
 
4
5
  @Injectable()
5
6
  export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
7
+ constructor() {
8
+ const url = process.env.DATABASE_URL;
9
+ if (isSqliteDatabaseUrl(url)) {
10
+ const client = new PrismaClient();
11
+ // Constructor return replaces `this` — extended client keeps full delegate API.
12
+ return client.$extends(
13
+ sqliteJsonCodecExtension() as Parameters<PrismaClient["$extends"]>[0]
14
+ ) as unknown as PrismaService;
15
+ }
16
+ super();
17
+ }
18
+
6
19
  async onModuleInit() {
7
20
  await this.$connect();
8
21
  }
@@ -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
- this.logger.info("request.completed", {
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
- this.logger.error("request.failed", {
57
+ logger.error("request.failed", {
56
58
  context: "http",
57
59
  method,
58
60
  path,