@verikit/prisma 0.23.1

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/LICENSE.md ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chidi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,107 @@
1
+ import type { FieldMap, RelationshipMap, Resource } from "@verikit/core";
2
+ import { type ResourceAdapter } from "@verikit/server";
3
+ /**
4
+ * Structural subset of a generated Prisma model delegate (e.g. `prisma.post`) that this
5
+ * adapter drives. Kept loose (`any` args/results) rather than imported from `@prisma/client`:
6
+ * a generated client's per-model argument/return types are specific to that model and schema,
7
+ * there's no exported type that describes "any model delegate" generically, and every real
8
+ * delegate is a structural superset of this anyway (same shape `@verikit/drizzle`'s
9
+ * `AnyDrizzleDatabase` uses for the same reason).
10
+ */
11
+ export interface PrismaModelDelegate {
12
+ findMany(args?: any): Promise<any[]>;
13
+ count(args?: any): Promise<number>;
14
+ findUnique(args: any): Promise<any>;
15
+ findFirst?(args: any): Promise<any>;
16
+ create(args: any): Promise<any>;
17
+ update(args: any): Promise<any>;
18
+ updateMany?(args: any): Promise<{
19
+ count: number;
20
+ }>;
21
+ updateManyAndReturn?(args: any): Promise<any[]>;
22
+ delete(args: any): Promise<any>;
23
+ deleteMany?(args: any): Promise<{
24
+ count: number;
25
+ }>;
26
+ }
27
+ /**
28
+ * Id coercion between the adapter's raw string path segment and the value Prisma's `where`
29
+ * expects. Unlike `@verikit/drizzle` (which introspects a real column's `dataType` to coerce
30
+ * automatically), a Prisma model delegate exposes no such runtime metadata, so this is
31
+ * explicit configuration rather than inference.
32
+ */
33
+ export interface PrismaIdConfig<TId = unknown> {
34
+ /** The Prisma scalar name of the model's primary (or other unique) id field. */
35
+ field: string;
36
+ /**
37
+ * Decodes a route-segment string into the value used in Prisma's `where`. Return
38
+ * `undefined` to signal the segment can never correspond to a real record (e.g. a
39
+ * non-numeric segment against an `Int` id), which lets `find`/`update`/`delete` report
40
+ * "missing" without even querying, mirroring `@verikit/drizzle`'s `coerceId`. Defaults to
41
+ * the identity function, which only suits a string-typed id (cuid/uuid); a numeric or
42
+ * composite id must supply this.
43
+ */
44
+ fromPath?: (segment: string) => TId | undefined;
45
+ /**
46
+ * Encodes the raw Prisma id value into the canonical string `id` returned to clients.
47
+ * Defaults to `String(value)`.
48
+ */
49
+ toPath?: (value: TId) => string;
50
+ }
51
+ /**
52
+ * Which case-insensitive search strategy `.searchable()` fields use. Prisma's `mode:
53
+ * "insensitive"` filter is only implemented for PostgreSQL (and MongoDB); passing it on
54
+ * SQLite or MySQL throws `PrismaClientValidationError` at query time. SQLite's own `contains`
55
+ * is already ASCII-case-insensitive without it; MySQL's case-sensitivity is a property of the
56
+ * column's collation, which Prisma can't override from the query API. Omit this (or pass
57
+ * `"sqlite"`/`"mysql"`, which take the same code path) unless the datasource is PostgreSQL.
58
+ * Only `"sqlite"` is exercised by this package's own test suite; `"postgresql"`'s branch is
59
+ * implemented per Prisma's documented behavior but isn't integration-tested here (no
60
+ * PostgreSQL instance in this repo's test environment) establish and test your own
61
+ * provider's search behavior before relying on it in production.
62
+ *
63
+ * Separately, unlike `@verikit/drizzle` (which escapes `%`/`_` in the search term before
64
+ * building its own `LIKE ... ESCAPE '\'`), this adapter's search goes through Prisma's
65
+ * `contains` filter, which has no escape-character option. A search term containing `%` or
66
+ * `_` is passed through and interpreted as a SQL wildcard by the underlying database, not
67
+ * matched literally. There's no adapter-level fix for this without dropping to raw SQL (and
68
+ * losing cross-provider portability with it); a consumer that needs literal-substring search
69
+ * semantics must filter or escape those characters itself before calling the adapter.
70
+ */
71
+ export type PrismaSearchProvider = "postgresql" | "sqlite" | "mysql";
72
+ export interface PrismaAdapterOptions<TFields extends FieldMap> {
73
+ /** The generated Prisma model delegate this adapter reads/writes, e.g. `prisma.post`. */
74
+ model: PrismaModelDelegate;
75
+ /**
76
+ * Required resource-field-to-Prisma-scalar mapping, covering every field the resource
77
+ * declares. Used for reads, writes, search, and sorting. There is no automatic
78
+ * same-name fallback (unlike `@verikit/drizzle`'s column resolution) because a Prisma
79
+ * delegate has no introspectable schema to fall back against; every field must be listed
80
+ * explicitly. Relation fields and arbitrary Prisma `include`/`select` values are out of
81
+ * scope see `ResourceAdapter`'s docstring on why relationship loading isn't part of this
82
+ * contract yet.
83
+ */
84
+ fields: {
85
+ [K in keyof TFields & string]: string;
86
+ };
87
+ /** Names the model's primary (or other unique) scalar and how to codec it. */
88
+ id: PrismaIdConfig;
89
+ /** See `PrismaSearchProvider`. */
90
+ provider?: PrismaSearchProvider;
91
+ }
92
+ /** A canonical API record returned by the Prisma adapter. */
93
+ export interface PrismaResourceRecord extends Record<string, unknown> {
94
+ /** The id, encoded via `id.toPath`, suitable for resource URLs. */
95
+ id: string;
96
+ }
97
+ /**
98
+ * Builds a `ResourceAdapter` backed by a Prisma model delegate, so `@verikit/server` never
99
+ * has to import `@prisma/client` itself. Every operation selects and returns only the
100
+ * configured `fields` plus the canonical `id` never a whole model row matching
101
+ * `ResourceAdapter`'s contract that adapter records are API records, not ORM rows.
102
+ * @throws {Error} If `fields` is missing a mapping for a field the resource declares, or if a
103
+ * `.searchable()` field's `fieldType` isn't text-like (`text`/`textarea`/`email`) Prisma's
104
+ * `contains` filter only works on `String` scalars.
105
+ */
106
+ export declare function createPrismaAdapter<TFields extends FieldMap, TRelationships extends RelationshipMap, TTable = unknown>(resource: Resource<string, TFields, TTable, TRelationships>, options: PrismaAdapterOptions<TFields>): ResourceAdapter<PrismaResourceRecord>;
107
+ //# sourceMappingURL=create-prisma-adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-prisma-adapter.d.ts","sourceRoot":"","sources":["../src/create-prisma-adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAEL,KAAK,eAAe,EAErB,MAAM,iBAAiB,CAAC;AAYzB;;;;;;;GAOG;AAEH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IACrC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnC,UAAU,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,SAAS,CAAC,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAChC,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAChC,UAAU,CAAC,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACnD,mBAAmB,CAAC,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;IAChD,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAChC,UAAU,CAAC,CAAC,IAAI,EAAE,GAAG,GAAG,OAAO,CAAC;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACpD;AAGD;;;;;GAKG;AACH,MAAM,WAAW,cAAc,CAAC,GAAG,GAAG,OAAO;IAC3C,gFAAgF;IAChF,KAAK,EAAE,MAAM,CAAC;IACd;;;;;;;OAOG;IACH,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,GAAG,GAAG,SAAS,CAAC;IAChD;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,KAAK,MAAM,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,MAAM,oBAAoB,GAAG,YAAY,GAAG,QAAQ,GAAG,OAAO,CAAC;AAErE,MAAM,WAAW,oBAAoB,CAAC,OAAO,SAAS,QAAQ;IAC5D,yFAAyF;IACzF,KAAK,EAAE,mBAAmB,CAAC;IAC3B;;;;;;;;OAQG;IACH,MAAM,EAAE;SAAG,CAAC,IAAI,MAAM,OAAO,GAAG,MAAM,GAAG,MAAM;KAAE,CAAC;IAClD,8EAA8E;IAC9E,EAAE,EAAE,cAAc,CAAC;IACnB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CACjC;AAED,6DAA6D;AAC7D,MAAM,WAAW,oBAAqB,SAAQ,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACnE,mEAAmE;IACnE,EAAE,EAAE,MAAM,CAAC;CACZ;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,SAAS,QAAQ,EACxB,cAAc,SAAS,eAAe,EACtC,MAAM,GAAG,OAAO,EAEhB,QAAQ,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,cAAc,CAAC,EAC3D,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,GACrC,eAAe,CAAC,oBAAoB,CAAC,CA6RvC"}
@@ -0,0 +1,223 @@
1
+ import { UniqueConstraintError, } from "@verikit/server";
2
+ import { buildSelect, isRecordNotFoundError, isUniqueConstraintError, mapFilterToPrisma, mapValuesToData, presentRow, uniqueConstraintFields, } from "./mapping.js";
3
+ /**
4
+ * Builds a `ResourceAdapter` backed by a Prisma model delegate, so `@verikit/server` never
5
+ * has to import `@prisma/client` itself. Every operation selects and returns only the
6
+ * configured `fields` plus the canonical `id` never a whole model row matching
7
+ * `ResourceAdapter`'s contract that adapter records are API records, not ORM rows.
8
+ * @throws {Error} If `fields` is missing a mapping for a field the resource declares, or if a
9
+ * `.searchable()` field's `fieldType` isn't text-like (`text`/`textarea`/`email`) Prisma's
10
+ * `contains` filter only works on `String` scalars.
11
+ */
12
+ export function createPrismaAdapter(resource, options) {
13
+ const { model, id } = options;
14
+ const fields = options.fields;
15
+ const schema = resource.toSchema();
16
+ const unmapped = Object.keys(schema.fields).filter((name) => !Object.hasOwn(fields, name));
17
+ if (unmapped.length > 0) {
18
+ throw new Error(`@verikit/prisma: resource "${resource.name}" has no Prisma field mapping for: ${unmapped.join(", ")}. Every declared field needs an entry in \`fields\`.`);
19
+ }
20
+ const searchableScalars = Object.entries(schema.fields)
21
+ .filter(([, field]) => field.searchable)
22
+ .map(([name, field]) => {
23
+ if (field.fieldType !== "text" &&
24
+ field.fieldType !== "textarea" &&
25
+ field.fieldType !== "email") {
26
+ throw new Error(`@verikit/prisma: resource "${resource.name}"'s searchable field "${name}" has fieldType "${field.fieldType}". Search only supports text fields.`);
27
+ }
28
+ return [name, fields[name]];
29
+ });
30
+ const select = buildSelect(fields, id.field);
31
+ const fromPath = id.fromPath ?? ((segment) => segment);
32
+ const toPath = id.toPath ?? ((value) => String(value));
33
+ function present(row) {
34
+ return row
35
+ ? presentRow(row, fields, id.field, toPath)
36
+ : undefined;
37
+ }
38
+ function searchWhere(term, searchable) {
39
+ const insensitive = options.provider === "postgresql";
40
+ return {
41
+ OR: searchable.map((scalar) => ({
42
+ [scalar]: insensitive
43
+ ? { contains: term, mode: "insensitive" }
44
+ : { contains: term },
45
+ })),
46
+ };
47
+ }
48
+ function scopeWhere(scope) {
49
+ if (!scope || Object.keys(scope).length === 0)
50
+ return undefined;
51
+ return Object.fromEntries(Object.entries(scope).map(([name, value]) => {
52
+ const scalar = fields[name];
53
+ if (!scalar) {
54
+ throw new Error(`@verikit/prisma: resource "${resource.name}" scope field "${name}" has no Prisma mapping.`);
55
+ }
56
+ return [scalar, value];
57
+ }));
58
+ }
59
+ function combinedWhere(scope, extra, filters) {
60
+ const filterWhere = filters
61
+ ? Object.fromEntries(Object.entries(filters).map(([name, filter]) => {
62
+ const scalar = fields[name];
63
+ if (!scalar) {
64
+ throw new Error(`@verikit/prisma: resource "${resource.name}" filter field "${name}" has no Prisma mapping.`);
65
+ }
66
+ return [scalar, mapFilterToPrisma(filter)];
67
+ }))
68
+ : undefined;
69
+ const constraints = [scopeWhere(scope), extra, filterWhere].filter(Boolean);
70
+ return constraints.length === 0
71
+ ? undefined
72
+ : constraints.length === 1
73
+ ? constraints[0]
74
+ : { AND: constraints };
75
+ }
76
+ return {
77
+ async list(params) {
78
+ // A search term against a resource with no searchable fields can never match
79
+ // anything; treat it as an unsatisfiable filter (zero results), matching
80
+ // @verikit/drizzle's convention for the same case.
81
+ const permittedSearchScalars = params.searchFields
82
+ ? searchableScalars
83
+ .filter(([name]) => params.searchFields.includes(name))
84
+ .map(([, scalar]) => scalar)
85
+ : searchableScalars.map(([, scalar]) => scalar);
86
+ if (params.search && permittedSearchScalars.length === 0) {
87
+ return { records: [], total: 0 };
88
+ }
89
+ const where = combinedWhere(params.scope, params.search
90
+ ? searchWhere(params.search, permittedSearchScalars)
91
+ : undefined, params.filters);
92
+ const sort = params.sort;
93
+ const sortScalar = sort && fields[sort.field];
94
+ const orderBy = sort && sortScalar ? { [sortScalar]: sort.direction } : undefined;
95
+ // Two independent queries, not one transaction: only the model delegate is
96
+ // available here, not the top-level PrismaClient that owns `$transaction`. A
97
+ // concurrent write between these two calls can make `total` and `records.length`
98
+ // momentarily disagree across a page boundary; a consumer that needs a consistent
99
+ // snapshot should pass a delegate bound to an active `$transaction` callback.
100
+ const [rows, total] = await Promise.all([
101
+ model.findMany({
102
+ where,
103
+ select,
104
+ ...(orderBy && { orderBy }),
105
+ skip: (params.page - 1) * params.pageSize,
106
+ take: params.pageSize,
107
+ }),
108
+ model.count({ where }),
109
+ ]);
110
+ return {
111
+ records: rows.map((row) => present(row)),
112
+ total,
113
+ };
114
+ },
115
+ async find(pathId, scope) {
116
+ const value = fromPath(pathId);
117
+ if (value === undefined) {
118
+ return undefined;
119
+ }
120
+ if (scope && !model.findFirst) {
121
+ throw new Error("@verikit/prisma: scoped reads require a Prisma delegate with findFirst().");
122
+ }
123
+ const row = scope
124
+ ? await model.findFirst({
125
+ where: combinedWhere(scope, { [id.field]: value }),
126
+ select,
127
+ })
128
+ : await model.findUnique({ where: { [id.field]: value }, select });
129
+ return present(row);
130
+ },
131
+ async create(values) {
132
+ const data = mapValuesToData(values, fields);
133
+ try {
134
+ const row = await model.create({ data, select });
135
+ return present(row);
136
+ }
137
+ catch (error) {
138
+ if (isUniqueConstraintError(error)) {
139
+ throw new UniqueConstraintError(uniqueConstraintFields(error, fields));
140
+ }
141
+ throw error;
142
+ }
143
+ },
144
+ async update(pathId, values, scope) {
145
+ const value = fromPath(pathId);
146
+ if (value === undefined) {
147
+ return undefined;
148
+ }
149
+ const data = mapValuesToData(values, fields);
150
+ // Prisma's update() only accepts a unique selector, so it cannot express
151
+ // `{ id, organizationId }`. updateMany/updateManyAndReturn make the tenant
152
+ // predicate atomic.
153
+ if (scope) {
154
+ const where = combinedWhere(scope, { [id.field]: value });
155
+ try {
156
+ // returns the written row directly,
157
+ // so the scoped write and the canonical-record read happen in one round
158
+ // trip instead of two. Older Prisma delegates fall back to updateMany
159
+ // plus a follow-up scoped find.
160
+ if (model.updateManyAndReturn) {
161
+ const [row] = await model.updateManyAndReturn({
162
+ where,
163
+ data,
164
+ select,
165
+ });
166
+ return present(row);
167
+ }
168
+ if (!model.updateMany) {
169
+ throw new Error("@verikit/prisma: scoped updates require a Prisma delegate with updateMany() or updateManyAndReturn().");
170
+ }
171
+ const result = await model.updateMany({ where, data });
172
+ return result.count === 0 ? undefined : this.find(pathId, scope);
173
+ }
174
+ catch (error) {
175
+ if (isUniqueConstraintError(error)) {
176
+ throw new UniqueConstraintError(uniqueConstraintFields(error, fields));
177
+ }
178
+ throw error;
179
+ }
180
+ }
181
+ try {
182
+ const row = await model.update({
183
+ where: { [id.field]: value },
184
+ data,
185
+ select,
186
+ });
187
+ return present(row);
188
+ }
189
+ catch (error) {
190
+ if (isRecordNotFoundError(error)) {
191
+ return undefined;
192
+ }
193
+ if (isUniqueConstraintError(error)) {
194
+ throw new UniqueConstraintError(uniqueConstraintFields(error, fields));
195
+ }
196
+ throw error;
197
+ }
198
+ },
199
+ async delete(pathId, scope) {
200
+ const value = fromPath(pathId);
201
+ if (value === undefined) {
202
+ return;
203
+ }
204
+ if (scope) {
205
+ if (!model.deleteMany) {
206
+ throw new Error("@verikit/prisma: scoped deletes require a Prisma delegate with deleteMany().");
207
+ }
208
+ await model.deleteMany({
209
+ where: combinedWhere(scope, { [id.field]: value }),
210
+ });
211
+ return;
212
+ }
213
+ try {
214
+ await model.delete({ where: { [id.field]: value } });
215
+ }
216
+ catch (error) {
217
+ if (!isRecordNotFoundError(error)) {
218
+ throw error;
219
+ }
220
+ }
221
+ },
222
+ };
223
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./create-prisma-adapter.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from "./create-prisma-adapter.js";
@@ -0,0 +1,52 @@
1
+ import type { ResourceFilter } from "@verikit/server";
2
+ /** Resource field name -> Prisma scalar name. */
3
+ export type PrismaFieldMap = Record<string, string>;
4
+ /**
5
+ * Translates a `ResourceFilter` (`eq`/`gte`/`gt`/`lte`/`lt`) into Prisma's own scalar filter
6
+ * shape. Only `eq` needs renaming (Prisma calls it `equals`); the range keys already match
7
+ * Prisma's own names, so they pass through unchanged.
8
+ */
9
+ export declare function mapFilterToPrisma(filter: ResourceFilter): Record<string, unknown>;
10
+ /**
11
+ * The only `select` this adapter ever sends: the configured resource fields plus the id
12
+ * field, and nothing else. There's no `include`/relation key here on purpose a Prisma
13
+ * adapter must not auto-include relations any more than the Drizzle adapter auto-joins
14
+ * them (see `ResourceAdapter`'s docstring in `@verikit/server`).
15
+ */
16
+ export declare function buildSelect(fields: PrismaFieldMap, idField: string): Record<string, true>;
17
+ /**
18
+ * Translates a Prisma row (keyed by Prisma scalar names, shaped by `buildSelect`) into the
19
+ * canonical API record: resource field names plus a string `id`. Since `select` never asks
20
+ * for anything outside `fields` + the id field, this can't leak an undeclared column even if
21
+ * a caller handed `row` more keys than expected.
22
+ */
23
+ export declare function presentRow(row: Record<string, unknown>, fields: PrismaFieldMap, idField: string, toPath: (value: unknown) => string): Record<string, unknown>;
24
+ /**
25
+ * Translates a create/update payload (keyed by resource field names, already validated by
26
+ * `@verikit/server`) into Prisma `data` (keyed by Prisma scalar names). A key outside
27
+ * `fields` is dropped rather than thrown on: `createPrismaAdapter` requires `fields` to map
28
+ * every declared resource field, so the only way to reach this case is a caller that
29
+ * bypasses that validation (e.g. calling the adapter directly, as this package's own tests
30
+ * do), matching `@verikit/drizzle`'s convention for the same situation.
31
+ */
32
+ export declare function mapValuesToData(values: Record<string, unknown>, fields: PrismaFieldMap): Record<string, unknown>;
33
+ /**
34
+ * True for Prisma's "record to update/delete not found" error (`P2025`). `ResourceAdapter`'s
35
+ * `update`/`delete` contract requires an adapter to catch this and translate it to the
36
+ * missing-record signal (`undefined` / a no-op) rather than let it propagate as an unhandled
37
+ * rejection. Checked structurally (`error.code`) instead of `instanceof
38
+ * Prisma.PrismaClientKnownRequestError` so this doesn't depend on which generated
39
+ * `@prisma/client` export path a consumer's Prisma version puts that class on.
40
+ */
41
+ export declare function isRecordNotFoundError(error: unknown): boolean;
42
+ /**
43
+ * True for Prisma's "unique constraint violated" error (`P2002`). Checked
44
+ * structurally for the same reason as `isRecordNotFoundError`.
45
+ */
46
+ export declare function isUniqueConstraintError(error: unknown): boolean;
47
+ /**
48
+ * Resolves a `P2002` error's offending scalar name(s) to resource field names via the
49
+ * adapter's field -> Prisma scalar map.
50
+ */
51
+ export declare function uniqueConstraintFields(error: unknown, fields: PrismaFieldMap): string[];
52
+ //# sourceMappingURL=mapping.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mapping.d.ts","sourceRoot":"","sources":["../src/mapping.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEtD,iDAAiD;AACjD,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEpD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,cAAc,GACrB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzB;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CACzB,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,MAAM,GACd,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,CAQtB;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC5B,MAAM,EAAE,cAAc,EACtB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,GACjC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAQzB;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAC/B,MAAM,EAAE,cAAc,GACrB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAYzB;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAO7D;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAO/D;AAqCD;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,OAAO,EACd,MAAM,EAAE,cAAc,GACrB,MAAM,EAAE,CAWV"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Translates a `ResourceFilter` (`eq`/`gte`/`gt`/`lte`/`lt`) into Prisma's own scalar filter
3
+ * shape. Only `eq` needs renaming (Prisma calls it `equals`); the range keys already match
4
+ * Prisma's own names, so they pass through unchanged.
5
+ */
6
+ export function mapFilterToPrisma(filter) {
7
+ const mapped = {};
8
+ if (filter.eq !== undefined)
9
+ mapped.equals = filter.eq;
10
+ if (filter.gte !== undefined)
11
+ mapped.gte = filter.gte;
12
+ if (filter.gt !== undefined)
13
+ mapped.gt = filter.gt;
14
+ if (filter.lte !== undefined)
15
+ mapped.lte = filter.lte;
16
+ if (filter.lt !== undefined)
17
+ mapped.lt = filter.lt;
18
+ return mapped;
19
+ }
20
+ /**
21
+ * The only `select` this adapter ever sends: the configured resource fields plus the id
22
+ * field, and nothing else. There's no `include`/relation key here on purpose a Prisma
23
+ * adapter must not auto-include relations any more than the Drizzle adapter auto-joins
24
+ * them (see `ResourceAdapter`'s docstring in `@verikit/server`).
25
+ */
26
+ export function buildSelect(fields, idField) {
27
+ const select = { [idField]: true };
28
+ for (const scalar of Object.values(fields)) {
29
+ select[scalar] = true;
30
+ }
31
+ return select;
32
+ }
33
+ /**
34
+ * Translates a Prisma row (keyed by Prisma scalar names, shaped by `buildSelect`) into the
35
+ * canonical API record: resource field names plus a string `id`. Since `select` never asks
36
+ * for anything outside `fields` + the id field, this can't leak an undeclared column even if
37
+ * a caller handed `row` more keys than expected.
38
+ */
39
+ export function presentRow(row, fields, idField, toPath) {
40
+ const record = { id: toPath(row[idField]) };
41
+ for (const [name, scalar] of Object.entries(fields)) {
42
+ record[name] = row[scalar];
43
+ }
44
+ return record;
45
+ }
46
+ /**
47
+ * Translates a create/update payload (keyed by resource field names, already validated by
48
+ * `@verikit/server`) into Prisma `data` (keyed by Prisma scalar names). A key outside
49
+ * `fields` is dropped rather than thrown on: `createPrismaAdapter` requires `fields` to map
50
+ * every declared resource field, so the only way to reach this case is a caller that
51
+ * bypasses that validation (e.g. calling the adapter directly, as this package's own tests
52
+ * do), matching `@verikit/drizzle`'s convention for the same situation.
53
+ */
54
+ export function mapValuesToData(values, fields) {
55
+ const data = {};
56
+ for (const [name, value] of Object.entries(values)) {
57
+ const scalar = fields[name];
58
+ if (scalar) {
59
+ data[scalar] = value;
60
+ }
61
+ }
62
+ return data;
63
+ }
64
+ /**
65
+ * True for Prisma's "record to update/delete not found" error (`P2025`). `ResourceAdapter`'s
66
+ * `update`/`delete` contract requires an adapter to catch this and translate it to the
67
+ * missing-record signal (`undefined` / a no-op) rather than let it propagate as an unhandled
68
+ * rejection. Checked structurally (`error.code`) instead of `instanceof
69
+ * Prisma.PrismaClientKnownRequestError` so this doesn't depend on which generated
70
+ * `@prisma/client` export path a consumer's Prisma version puts that class on.
71
+ */
72
+ export function isRecordNotFoundError(error) {
73
+ return (typeof error === "object" &&
74
+ error !== null &&
75
+ "code" in error &&
76
+ error.code === "P2025");
77
+ }
78
+ /**
79
+ * True for Prisma's "unique constraint violated" error (`P2002`). Checked
80
+ * structurally for the same reason as `isRecordNotFoundError`.
81
+ */
82
+ export function isUniqueConstraintError(error) {
83
+ return (typeof error === "object" &&
84
+ error !== null &&
85
+ "code" in error &&
86
+ error.code === "P2002");
87
+ }
88
+ /**
89
+ * Reads the offending scalar name(s) off a `P2002` error, wherever the running Prisma
90
+ * version put them. Prisma 6 (and any client on a direct datasource connection) reports
91
+ * `meta.target`: an array of scalar names on Postgres/SQLite, or the constraint's own name
92
+ * as a single string on MySQL (which won't match any scalar, and is filtered out below
93
+ * rather than mismapped). Prisma 7's mandatory driver-adapter architecture instead nests
94
+ * them under `meta.driverAdapterError.cause.constraint.fields`, checked first since it's
95
+ * this package's actual (SQLite driver-adapter) test path.
96
+ */
97
+ function uniqueConstraintScalars(error) {
98
+ const meta = error.meta;
99
+ const driverAdapterFields = meta?.driverAdapterError?.cause?.constraint?.fields;
100
+ if (Array.isArray(driverAdapterFields)) {
101
+ return driverAdapterFields.filter((entry) => typeof entry === "string");
102
+ }
103
+ const target = meta?.target;
104
+ return Array.isArray(target)
105
+ ? target.filter((entry) => typeof entry === "string")
106
+ : typeof target === "string"
107
+ ? [target]
108
+ : [];
109
+ }
110
+ /**
111
+ * Resolves a `P2002` error's offending scalar name(s) to resource field names via the
112
+ * adapter's field -> Prisma scalar map.
113
+ */
114
+ export function uniqueConstraintFields(error, fields) {
115
+ const scalars = uniqueConstraintScalars(error);
116
+ const resolved = scalars
117
+ .map((scalar) => Object.entries(fields).find(([, value]) => value === scalar)?.[0])
118
+ .filter((name) => name !== undefined);
119
+ return resolved.length > 0 ? resolved : scalars;
120
+ }
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@verikit/prisma",
3
+ "version": "0.23.1",
4
+ "description": "Prisma ORM storage adapter for @verikit/server resources.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "keywords": [
8
+ "typescript",
9
+ "resource",
10
+ "schema",
11
+ "resource-model",
12
+ "metadata",
13
+ "builder",
14
+ "validation",
15
+ "framework",
16
+ "prisma"
17
+ ],
18
+ "author": "Chidi E <hi@ceeso.dev>",
19
+ "license": "MIT",
20
+ "engines": {
21
+ "node": ">=24"
22
+ },
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "dependencies": {
34
+ "@verikit/core": "0.23.1",
35
+ "@verikit/server": "0.23.1"
36
+ },
37
+ "devDependencies": {
38
+ "@prisma/adapter-better-sqlite3": "^7.9.1",
39
+ "@prisma/client": "^7.9.1",
40
+ "@types/node": "^26.1.1",
41
+ "prisma": "^7.9.1",
42
+ "typescript": "^6.0.3"
43
+ },
44
+ "peerDependencies": {
45
+ "@prisma/client": "^6.0.0 || ^7.0.0"
46
+ },
47
+ "scripts": {
48
+ "clean": "rm -rf dist tsconfig.tsbuildinfo",
49
+ "build": "pnpm clean && tsc -b",
50
+ "pretest": "prisma generate --schema=./test/prisma/schema.prisma",
51
+ "test": "rm -rf .test-dist && tsc -p tsconfig.test.json && node --test $(find ./.test-dist/test -name '*.test.js' -type f | sort)",
52
+ "pretest:coverage": "prisma generate --schema=./test/prisma/schema.prisma",
53
+ "test:coverage": "rm -rf .test-dist coverage && tsc -p tsconfig.test.json && node --test --experimental-test-coverage --test-coverage-include='.test-dist/src/**/*.js' --test-coverage-lines=100 --test-coverage-branches=100 --test-coverage-functions=100 $(find ./.test-dist/test -name '*.test.js' -type f | sort)"
54
+ }
55
+ }