@telamonjs/data 1.0.1 → 1.1.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 5fd314b: New `@telamonjs/data/nest` entry (needs `@nestjs/common` 10 or 11, an optional peer; never imports `@prisma/client`). `PrismaExceptionFilter` answers Prisma errors with HTTP statuses (P2002 → 409 with `field`, P2003 → 400, P2025 → 404, P2011/P2012/P2014 and validation errors → 400, P1000–P1003 → 503, other codes → 500 logged), matching them by shape so only Prisma errors reach it; English messages, overridable per code with `messages`. `HealthModule.forRoot({ checks, inject?, imports?, path?, decorators? })` serves `GET /health` with `{ status, timestamp, uptime, <check>: 'connected' | 'disconnected' }` and answers 503 when a check is down. The monorepo template's API now uses both instead of its own filter and health controller, and requires Node 22.12+.
8
+
3
9
  ## 1.0.1
4
10
 
5
11
  ### Patch Changes
package/README.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  The server half of a TelamonJS list. A `ListPage` sends page, page size, search, sort and filters.
4
4
  This package reads them on the endpoint and turns them into a query, with no dependencies and
5
- without React, Next or Prisma.
5
+ without React, Next or Prisma. A NestJS API also gets the Prisma exception filter and health
6
+ endpoint every API repeats.
6
7
 
7
8
  ```bash
8
9
  pnpm add @telamonjs/data
@@ -12,6 +13,7 @@ pnpm add @telamonjs/data
12
13
  | --- | --- | --- |
13
14
  | `@telamonjs/data` | The wire contract (`PaginationParams`, `PaginatedResponse`, `SortField`, `createPaginatedResponse`), `sanitizePaginationParams`, `resolveSort`, `resolveSortPath` | No |
14
15
  | `@telamonjs/data/prisma` | `buildPrismaOrderBy(Multi)`, `buildSearchConditions`, `buildFilterConditions`, `buildWhereClause`, `createPaginationContext` | Builds Prisma's object shape; never imports `@prisma/client` |
16
+ | `@telamonjs/data/nest` | `PrismaExceptionFilter`, `HealthModule`, `isPrismaKnownRequestError`, `isPrismaValidationError` | Needs `@nestjs/common` (optional peer); never imports `@prisma/client` |
15
17
 
16
18
  ## Sorting what a list sends
17
19
 
@@ -87,6 +89,73 @@ export const customers = createPaginatedService({
87
89
  `@telamonjs/ui/server` re-exports these helpers for Next.js server code. A NestJS or plain Node
88
90
  API installs only this package.
89
91
 
92
+ ## NestJS (`@telamonjs/data/nest`)
93
+
94
+ Needs `@nestjs/common` 10 or 11, an optional peer that only this entry imports.
95
+
96
+ ### Prisma errors as HTTP statuses
97
+
98
+ `PrismaExceptionFilter` answers Prisma errors with a status instead of a 500. It matches
99
+ Prisma's known-request and validation errors by shape (`code` + `name`/`clientVersion`), so it
100
+ works with any `@prisma/client` copy, and it never claims other errors: your own filters and
101
+ Nest's default handling still get them.
102
+
103
+ ```ts
104
+ import { PrismaExceptionFilter } from '@telamonjs/data/nest'
105
+
106
+ app.useGlobalFilters(new PrismaExceptionFilter())
107
+ ```
108
+
109
+ | Prisma | HTTP |
110
+ | --- | --- |
111
+ | `P2002` unique | 409, `field` = first `target` field |
112
+ | `P2003` foreign key | 400, `field` = constraint |
113
+ | `P2025` not found | 404 |
114
+ | `P2011`, `P2012`, `P2014`, `PrismaClientValidationError` | 400 |
115
+ | `P1000`–`P1003` connection | 503 |
116
+ | any other code | 500, logged with Nest's `Logger` |
117
+
118
+ The body is `{ statusCode, message, error, field?, timestamp, path }`, written with Express's
119
+ `res.status().json()`. Outside HTTP (RPC, WebSocket, GraphQL) the error is rethrown. Messages are
120
+ English; replace them (in your app's language, say) per code, `validation` or `default`, with a
121
+ string or a function of the reported fields:
122
+
123
+ ```ts
124
+ new PrismaExceptionFilter({
125
+ messages: {
126
+ P2025: 'Nothing here',
127
+ P2002: (fields) => `${fields.join(', ')} is already taken`,
128
+ },
129
+ })
130
+ ```
131
+
132
+ To change one case (say, `P2003` on a `DELETE` as 409), subclass it, handle that case in `catch`
133
+ and call `super.catch(exception, host)` for the rest.
134
+
135
+ ### Health endpoint
136
+
137
+ `HealthModule.forRoot()` serves `GET /health`. It runs the checks in parallel and answers 200, or
138
+ 503 with `status: 'error'` when any check is down, so Docker and load balancers can read the
139
+ status code:
140
+
141
+ ```ts
142
+ import { Public } from '@telamonjs/auth/nest'
143
+ import { HealthModule } from '@telamonjs/data/nest'
144
+
145
+ HealthModule.forRoot({
146
+ decorators: [Public()], // class decorators for the controller
147
+ inject: [PrismaService, REDIS],
148
+ checks: (prisma: PrismaService, redis: Redis) => ({
149
+ database: () => prisma.$queryRaw`SELECT 1`,
150
+ redis: () => redis.ping(),
151
+ }),
152
+ })
153
+ // GET /health → { status: 'ok', timestamp, uptime, database: 'connected', redis: 'connected' }
154
+ ```
155
+
156
+ A check is down when it throws, rejects or resolves `false`. `path` changes the route (default
157
+ `'health'`); `imports` brings in the modules of the `inject` tokens when they are not global.
158
+
90
159
  ## License
91
160
 
92
161
  MIT
@@ -0,0 +1,53 @@
1
+ import { type DynamicModule, type InjectionToken, type ModuleMetadata, type OptionalFactoryDependency } from '@nestjs/common';
2
+ /** One probe: resolving `false`, rejecting or throwing means down; anything else means up. */
3
+ export type HealthCheck = () => unknown;
4
+ /** Probes by name; each name becomes a key of the response (`database`, `redis`, …). */
5
+ export type HealthChecks = Record<string, HealthCheck>;
6
+ /** `GET /health` body: `status`, `timestamp`, `uptime`, then each check as `connected` | `disconnected`. */
7
+ export interface HealthResponse {
8
+ status: 'ok' | 'error';
9
+ timestamp: string;
10
+ /** `process.uptime()`, in seconds. */
11
+ uptime: number;
12
+ [check: string]: string | number;
13
+ }
14
+ export interface HealthModuleOptions {
15
+ /**
16
+ * Builds the probes from the injected `inject` tokens, in order (the same
17
+ * convention as a Nest `useFactory`):
18
+ *
19
+ * ```ts
20
+ * inject: [PrismaService],
21
+ * checks: (prisma: PrismaService) => ({ database: () => prisma.$queryRaw`SELECT 1` }),
22
+ * ```
23
+ */
24
+ checks: (...deps: never[]) => HealthChecks | Promise<HealthChecks>;
25
+ /** Tokens passed to `checks`. */
26
+ inject?: Array<InjectionToken | OptionalFactoryDependency>;
27
+ /** Modules that provide the `inject` tokens, when they are not global. */
28
+ imports?: ModuleMetadata['imports'];
29
+ /** Route of the controller. Default `'health'`. */
30
+ path?: string;
31
+ /**
32
+ * Class decorators applied to the controller, e.g. the auth package's
33
+ * `@Public()` or `@SkipThrottle()`. This package imports no auth.
34
+ */
35
+ decorators?: ClassDecorator[];
36
+ }
37
+ /**
38
+ * `GET /health`: runs every check in parallel and answers 200 when all are up,
39
+ * 503 (same body, `status: 'error'`) when any is down, so Docker and load
40
+ * balancer health checks can read the status code.
41
+ *
42
+ * ```ts
43
+ * HealthModule.forRoot({
44
+ * decorators: [Public()],
45
+ * inject: [PrismaService],
46
+ * checks: (prisma: PrismaService) => ({ database: () => prisma.$queryRaw`SELECT 1` }),
47
+ * })
48
+ * ```
49
+ */
50
+ export declare class HealthModule {
51
+ static forRoot(options: HealthModuleOptions): DynamicModule;
52
+ }
53
+ //# sourceMappingURL=health.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.module.d.ts","sourceRoot":"","sources":["../../src/nest/health.module.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,aAAa,EAClB,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,yBAAyB,EAC/B,MAAM,gBAAgB,CAAA;AAEvB,8FAA8F;AAC9F,MAAM,MAAM,WAAW,GAAG,MAAM,OAAO,CAAA;AAEvC,wFAAwF;AACxF,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;AAEtD,4GAA4G;AAC5G,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,IAAI,GAAG,OAAO,CAAA;IACtB,SAAS,EAAE,MAAM,CAAA;IACjB,sCAAsC;IACtC,MAAM,EAAE,MAAM,CAAA;IACd,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAA;CACjC;AAED,MAAM,WAAW,mBAAmB;IAClC;;;;;;;;OAQG;IACH,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,KAAK,EAAE,KAAK,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC,CAAA;IAClE,iCAAiC;IACjC,MAAM,CAAC,EAAE,KAAK,CAAC,cAAc,GAAG,yBAAyB,CAAC,CAAA;IAC1D,0EAA0E;IAC1E,OAAO,CAAC,EAAE,cAAc,CAAC,SAAS,CAAC,CAAA;IACnC,mDAAmD;IACnD,IAAI,CAAC,EAAE,MAAM,CAAA;IACb;;;OAGG;IACH,UAAU,CAAC,EAAE,cAAc,EAAE,CAAA;CAC9B;AAaD;;;;;;;;;;;;GAYG;AACH,qBACa,YAAY;IACvB,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,aAAa;CAwC5D"}
@@ -0,0 +1,89 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ var HealthModule_1;
11
+ import { Controller, Get, Inject, Module, Res, } from '@nestjs/common';
12
+ const HEALTH_CHECKS = Symbol('HEALTH_CHECKS');
13
+ const RESERVED = ['status', 'timestamp', 'uptime'];
14
+ async function probe(check) {
15
+ try {
16
+ return (await check()) === false ? 'disconnected' : 'connected';
17
+ }
18
+ catch {
19
+ return 'disconnected';
20
+ }
21
+ }
22
+ /**
23
+ * `GET /health`: runs every check in parallel and answers 200 when all are up,
24
+ * 503 (same body, `status: 'error'`) when any is down, so Docker and load
25
+ * balancer health checks can read the status code.
26
+ *
27
+ * ```ts
28
+ * HealthModule.forRoot({
29
+ * decorators: [Public()],
30
+ * inject: [PrismaService],
31
+ * checks: (prisma: PrismaService) => ({ database: () => prisma.$queryRaw`SELECT 1` }),
32
+ * })
33
+ * ```
34
+ */
35
+ let HealthModule = HealthModule_1 = class HealthModule {
36
+ static forRoot(options) {
37
+ let HealthController = class HealthController {
38
+ checks;
39
+ constructor(checks) {
40
+ this.checks = checks;
41
+ }
42
+ async check(res) {
43
+ const results = await Promise.all(Object.entries(this.checks).map(async ([name, check]) => [name, await probe(check)]));
44
+ const down = results.some(([, state]) => state === 'disconnected');
45
+ if (down)
46
+ res.status(503);
47
+ return {
48
+ status: down ? 'error' : 'ok',
49
+ timestamp: new Date().toISOString(),
50
+ uptime: process.uptime(),
51
+ ...Object.fromEntries(results),
52
+ };
53
+ }
54
+ };
55
+ __decorate([
56
+ Get(),
57
+ __param(0, Res({ passthrough: true }))
58
+ ], HealthController.prototype, "check", null);
59
+ HealthController = __decorate([
60
+ Controller(options.path ?? 'health'),
61
+ __param(0, Inject(HEALTH_CHECKS))
62
+ ], HealthController);
63
+ for (const decorate of options.decorators ?? [])
64
+ decorate(HealthController);
65
+ return {
66
+ module: HealthModule_1,
67
+ imports: options.imports ?? [],
68
+ controllers: [HealthController],
69
+ providers: [
70
+ {
71
+ provide: HEALTH_CHECKS,
72
+ inject: options.inject ?? [],
73
+ useFactory: async (...deps) => {
74
+ const checks = await options.checks(...deps);
75
+ const clash = Object.keys(checks).find((name) => RESERVED.includes(name));
76
+ if (clash)
77
+ throw new Error(`HealthModule: a check cannot be named "${clash}"`);
78
+ return checks;
79
+ },
80
+ },
81
+ ],
82
+ };
83
+ }
84
+ };
85
+ HealthModule = HealthModule_1 = __decorate([
86
+ Module({})
87
+ ], HealthModule);
88
+ export { HealthModule };
89
+ //# sourceMappingURL=health.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health.module.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AO,MAAM,CAAA;oBACf,CAAC;iBACF;aACF;SACF,CAAA;IACH,CAAC;CACF,CAAA;AAzCY,YAAY;IADxB,MAAM,CAAC,EAAE,CAAC;GACE,YAAY,CAyCxB"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@telamonjs/data/nest` — the NestJS + Prisma plumbing every API repeats:
3
+ * a Prisma exception filter and a health module. Needs `@nestjs/common`
4
+ * (optional peer); never imports `@prisma/client` — the app passes its client.
5
+ *
6
+ * @module data/nest
7
+ */
8
+ export type { PrismaKnownRequestErrorLike, PrismaValidationErrorLike, PrismaErrorMessage, PrismaExceptionFilterOptions, } from './prisma-exception.filter.js';
9
+ export { PrismaExceptionFilter, isPrismaKnownRequestError, isPrismaValidationError, } from './prisma-exception.filter.js';
10
+ export type { HealthCheck, HealthChecks, HealthResponse, HealthModuleOptions } from './health.module.js';
11
+ export { HealthModule } from './health.module.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/nest/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,YAAY,EACV,2BAA2B,EAC3B,yBAAyB,EACzB,kBAAkB,EAClB,4BAA4B,GAC7B,MAAM,8BAA8B,CAAA;AACrC,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,8BAA8B,CAAA;AACrC,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `@telamonjs/data/nest` — the NestJS + Prisma plumbing every API repeats:
3
+ * a Prisma exception filter and a health module. Needs `@nestjs/common`
4
+ * (optional peer); never imports `@prisma/client` — the app passes its client.
5
+ *
6
+ * @module data/nest
7
+ */
8
+ export { PrismaExceptionFilter, isPrismaKnownRequestError, isPrismaValidationError, } from './prisma-exception.filter.js';
9
+ export { HealthModule } from './health.module.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/nest/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,OAAO,EACL,qBAAqB,EACrB,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,8BAA8B,CAAA;AAErC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,67 @@
1
+ import { type ArgumentsHost, type ExceptionFilter } from '@nestjs/common';
2
+ /** Shape of Prisma's `PrismaClientKnownRequestError`, read without importing `@prisma/client`. */
3
+ export interface PrismaKnownRequestErrorLike {
4
+ name: string;
5
+ message: string;
6
+ /** `P` + four digits, e.g. `P2002`. */
7
+ code: string;
8
+ clientVersion?: string;
9
+ meta?: Record<string, unknown>;
10
+ }
11
+ /** Shape of Prisma's `PrismaClientValidationError`. */
12
+ export interface PrismaValidationErrorLike {
13
+ name: 'PrismaClientValidationError';
14
+ message: string;
15
+ }
16
+ /**
17
+ * `true` for a `PrismaClientKnownRequestError` from any `@prisma/client` copy:
18
+ * a `P####` code plus Prisma's `name` or `clientVersion`. A bare `code: 'P2002'`
19
+ * on some other error does not count.
20
+ */
21
+ export declare function isPrismaKnownRequestError(value: unknown): value is PrismaKnownRequestErrorLike;
22
+ /** `true` for a `PrismaClientValidationError` from any `@prisma/client` copy. */
23
+ export declare function isPrismaValidationError(value: unknown): value is PrismaValidationErrorLike;
24
+ /**
25
+ * Text of a response: a literal, or built from the fields Prisma reports
26
+ * (`meta.target` for `P2002`, `meta.field_name` for `P2003`, empty otherwise).
27
+ */
28
+ export type PrismaErrorMessage = string | ((fields: string[], error: PrismaKnownRequestErrorLike | PrismaValidationErrorLike) => string);
29
+ export interface PrismaExceptionFilterOptions {
30
+ /**
31
+ * Replaces the English default text, keyed by Prisma code (`P2002`, …),
32
+ * `validation` (`PrismaClientValidationError`) or `default` (a code this
33
+ * filter does not map, answered with 500).
34
+ */
35
+ messages?: Partial<Record<string, PrismaErrorMessage>>;
36
+ }
37
+ /**
38
+ * Answers Prisma errors with an HTTP status instead of a 500. Catches only
39
+ * Prisma's known-request and validation errors (matched by shape, so a second
40
+ * `@prisma/client` copy works too); every other error still reaches your other
41
+ * filters and Nest's default handling.
42
+ *
43
+ * | Prisma | HTTP |
44
+ * | --- | --- |
45
+ * | `P2002` unique | 409, `field` = first target field |
46
+ * | `P2003` foreign key | 400, `field` = constraint |
47
+ * | `P2025` not found | 404 |
48
+ * | `P2011`, `P2012`, `P2014`, validation error | 400 |
49
+ * | `P1000`–`P1003` connection | 503 |
50
+ * | any other code | 500, logged |
51
+ *
52
+ * Body: `{ statusCode, message, error, field?, timestamp, path }`. Written with
53
+ * Express's `res.status().json()`. Outside HTTP the error is rethrown.
54
+ *
55
+ * ```ts
56
+ * app.useGlobalFilters(new PrismaExceptionFilter({ messages: { P2025: 'Nothing here' } }))
57
+ * ```
58
+ *
59
+ * Subclass and override `catch` to change one case and call `super.catch` for the rest.
60
+ */
61
+ export declare class PrismaExceptionFilter implements ExceptionFilter {
62
+ private readonly options;
63
+ private readonly logger;
64
+ constructor(options?: PrismaExceptionFilterOptions);
65
+ catch(exception: unknown, host: ArgumentsHost): void;
66
+ }
67
+ //# sourceMappingURL=prisma-exception.filter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-exception.filter.d.ts","sourceRoot":"","sources":["../../src/nest/prisma-exception.filter.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,KAAK,aAAa,EAAE,KAAK,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAExF,kGAAkG;AAClG,MAAM,WAAW,2BAA2B;IAC1C,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;IACf,uCAAuC;IACvC,IAAI,EAAE,MAAM,CAAA;IACZ,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC/B;AAED,uDAAuD;AACvD,MAAM,WAAW,yBAAyB;IACxC,IAAI,EAAE,6BAA6B,CAAA;IACnC,OAAO,EAAE,MAAM,CAAA;CAChB;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,2BAA2B,CAQ9F;AAED,iFAAiF;AACjF,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,yBAAyB,CAM1F;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAC1B,MAAM,GACN,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,2BAA2B,GAAG,yBAAyB,KAAK,MAAM,CAAC,CAAA;AAElG,MAAM,WAAW,4BAA4B;IAC3C;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC,CAAA;CACvD;AA+CD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,qBACa,qBAAsB,YAAW,eAAe;IAG/C,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFpC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;gBAEhC,OAAO,GAAE,4BAAiC;IAEvE,KAAK,CAAC,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,aAAa,GAAG,IAAI;CA0BrD"}
@@ -0,0 +1,126 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { Catch, Logger } from '@nestjs/common';
8
+ /**
9
+ * `true` for a `PrismaClientKnownRequestError` from any `@prisma/client` copy:
10
+ * a `P####` code plus Prisma's `name` or `clientVersion`. A bare `code: 'P2002'`
11
+ * on some other error does not count.
12
+ */
13
+ export function isPrismaKnownRequestError(value) {
14
+ if (typeof value !== 'object' || value === null)
15
+ return false;
16
+ const { code, name, clientVersion } = value;
17
+ return (typeof code === 'string' &&
18
+ /^P\d{4}$/.test(code) &&
19
+ (name === 'PrismaClientKnownRequestError' || typeof clientVersion === 'string'));
20
+ }
21
+ /** `true` for a `PrismaClientValidationError` from any `@prisma/client` copy. */
22
+ export function isPrismaValidationError(value) {
23
+ return (typeof value === 'object' &&
24
+ value !== null &&
25
+ value.name === 'PrismaClientValidationError');
26
+ }
27
+ /** Matches a Prisma error by shape: Nest picks a filter with `instanceof`, which calls this. */
28
+ class PrismaErrorShape {
29
+ static [Symbol.hasInstance](value) {
30
+ return isPrismaKnownRequestError(value) || isPrismaValidationError(value);
31
+ }
32
+ }
33
+ const REASON = {
34
+ 400: 'Bad Request',
35
+ 404: 'Not Found',
36
+ 409: 'Conflict',
37
+ 500: 'Internal Server Error',
38
+ 503: 'Service Unavailable',
39
+ };
40
+ const CONNECTION = { status: 503, message: 'Database connection error' };
41
+ const RULES = {
42
+ P2002: {
43
+ status: 409,
44
+ message: (f) => (f.length ? `Duplicate record: ${f.join(', ')} already exists` : 'Duplicate record'),
45
+ },
46
+ P2003: { status: 400, message: (f) => `Invalid reference: ${f[0] ?? 'related record'} does not exist` },
47
+ P2025: { status: 404, message: 'Record not found' },
48
+ P2011: { status: 400, message: 'Invalid data: a required value is missing' },
49
+ P2012: { status: 400, message: 'Invalid data: a required value is missing' },
50
+ P2014: { status: 400, message: 'Cannot delete: the record is referenced by other records' },
51
+ P1000: CONNECTION,
52
+ P1001: CONNECTION,
53
+ P1002: CONNECTION,
54
+ P1003: CONNECTION,
55
+ validation: { status: 400, message: 'Invalid data' },
56
+ default: { status: 500, message: 'Internal server error' },
57
+ };
58
+ /** The fields a Prisma error names: the unique `target` (P2002) or the foreign key (P2003). */
59
+ function fieldsOf(meta) {
60
+ const raw = meta?.target ?? meta?.field_name;
61
+ if (Array.isArray(raw))
62
+ return raw.map(String);
63
+ return typeof raw === 'string' ? [raw] : [];
64
+ }
65
+ /**
66
+ * Answers Prisma errors with an HTTP status instead of a 500. Catches only
67
+ * Prisma's known-request and validation errors (matched by shape, so a second
68
+ * `@prisma/client` copy works too); every other error still reaches your other
69
+ * filters and Nest's default handling.
70
+ *
71
+ * | Prisma | HTTP |
72
+ * | --- | --- |
73
+ * | `P2002` unique | 409, `field` = first target field |
74
+ * | `P2003` foreign key | 400, `field` = constraint |
75
+ * | `P2025` not found | 404 |
76
+ * | `P2011`, `P2012`, `P2014`, validation error | 400 |
77
+ * | `P1000`–`P1003` connection | 503 |
78
+ * | any other code | 500, logged |
79
+ *
80
+ * Body: `{ statusCode, message, error, field?, timestamp, path }`. Written with
81
+ * Express's `res.status().json()`. Outside HTTP the error is rethrown.
82
+ *
83
+ * ```ts
84
+ * app.useGlobalFilters(new PrismaExceptionFilter({ messages: { P2025: 'Nothing here' } }))
85
+ * ```
86
+ *
87
+ * Subclass and override `catch` to change one case and call `super.catch` for the rest.
88
+ */
89
+ let PrismaExceptionFilter = class PrismaExceptionFilter {
90
+ options;
91
+ logger = new Logger('PrismaExceptionFilter');
92
+ constructor(options = {}) {
93
+ this.options = options;
94
+ }
95
+ catch(exception, host) {
96
+ if (host.getType() !== 'http')
97
+ throw exception;
98
+ if (!isPrismaKnownRequestError(exception) && !isPrismaValidationError(exception))
99
+ throw exception;
100
+ const known = isPrismaKnownRequestError(exception);
101
+ const key = known ? (exception.code in RULES ? exception.code : 'default') : 'validation';
102
+ if (known && key === 'default') {
103
+ this.logger.error(`Unmapped Prisma error ${exception.code}: ${exception.message}`, exception.stack);
104
+ }
105
+ const fields = known ? fieldsOf(exception.meta) : [];
106
+ const rule = RULES[key];
107
+ const text = this.options.messages?.[key] ?? rule.message;
108
+ const http = host.switchToHttp();
109
+ http
110
+ .getResponse()
111
+ .status(rule.status)
112
+ .json({
113
+ statusCode: rule.status,
114
+ message: typeof text === 'function' ? text(fields, exception) : text,
115
+ error: REASON[rule.status],
116
+ ...((key === 'P2002' || key === 'P2003') && fields.length > 0 && { field: fields[0] }),
117
+ timestamp: new Date().toISOString(),
118
+ path: http.getRequest().url,
119
+ });
120
+ }
121
+ };
122
+ PrismaExceptionFilter = __decorate([
123
+ Catch(PrismaErrorShape)
124
+ ], PrismaExceptionFilter);
125
+ export { PrismaExceptionFilter };
126
+ //# sourceMappingURL=prisma-exception.filter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prisma-exception.filter.js","sourceRoot":"","sources":["../../src/nest/prisma-exception.filter.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAA4C,MAAM,gBAAgB,CAAA;AAkBxF;;;;GAIG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAA;IAC7D,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,aAAa,EAAE,GAAG,KAAgC,CAAA;IACtE,OAAO,CACL,OAAO,IAAI,KAAK,QAAQ;QACxB,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC;QACrB,CAAC,IAAI,KAAK,+BAA+B,IAAI,OAAO,aAAa,KAAK,QAAQ,CAAC,CAChF,CAAA;AACH,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,uBAAuB,CAAC,KAAc;IACpD,OAAO,CACL,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACb,KAA4B,CAAC,IAAI,KAAK,6BAA6B,CACrE,CAAA;AACH,CAAC;AAmBD,gGAAgG;AAChG,MAAM,gBAAgB;IACpB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a TelamonJS list: the ListPage wire contract, sort and paging sanitizers, and a Prisma adapter (orderBy, scope-safe where, paginated services). Zero dependencies",
3
+ "version": "1.1.0",
4
+ "description": "The server half of a TelamonJS list: the ListPage wire contract, sort and paging sanitizers, a Prisma adapter (orderBy, scope-safe where, paginated services) and NestJS plumbing (Prisma exception filter, health module). Zero dependencies",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -16,12 +16,20 @@
16
16
  "types": "./dist/prisma/index.d.ts",
17
17
  "import": "./dist/prisma/index.js",
18
18
  "require": "./dist/prisma/index.js"
19
+ },
20
+ "./nest": {
21
+ "types": "./dist/nest/index.d.ts",
22
+ "import": "./dist/nest/index.js",
23
+ "require": "./dist/nest/index.js"
19
24
  }
20
25
  },
21
26
  "typesVersions": {
22
27
  "*": {
23
28
  "prisma": [
24
29
  "./dist/prisma/index.d.ts"
30
+ ],
31
+ "nest": [
32
+ "./dist/nest/index.d.ts"
25
33
  ]
26
34
  }
27
35
  },
@@ -31,17 +39,34 @@
31
39
  "prisma",
32
40
  "orderby",
33
41
  "data-provider",
42
+ "nestjs",
34
43
  "admin",
35
44
  "telamonjs",
36
45
  "typescript"
37
46
  ],
38
47
  "author": "Marcos Tullyo (https://github.com/mtullyoc)",
39
48
  "license": "MIT",
49
+ "peerDependencies": {
50
+ "@nestjs/common": "^10.0.0 || ^11.0.0"
51
+ },
52
+ "peerDependenciesMeta": {
53
+ "@nestjs/common": {
54
+ "optional": true
55
+ }
56
+ },
40
57
  "devDependencies": {
58
+ "@nestjs/common": "^11.1.19",
59
+ "@nestjs/core": "^11.1.19",
60
+ "@nestjs/platform-express": "^11.1.19",
61
+ "@nestjs/testing": "^11.1.19",
62
+ "@prisma/client": "6.2.0",
41
63
  "@types/node": "^20.19.21",
64
+ "@types/supertest": "^7.2.1",
42
65
  "@vitest/coverage-v8": "^3.2.4",
43
66
  "eslint": "^9.37.0",
44
67
  "prettier": "^3.10.1",
68
+ "reflect-metadata": "^0.2.2",
69
+ "supertest": "^7.3.2",
45
70
  "typescript": "^5.9.3",
46
71
  "vitest": "^3.2.4"
47
72
  },