@zenstackhq/server 3.5.6 → 3.6.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/dist/api.cjs +2729 -4451
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +219 -207
- package/dist/api.d.mts +249 -0
- package/dist/api.mjs +2745 -0
- package/dist/api.mjs.map +1 -0
- package/dist/common-BjzwQE8S.d.mts +16 -0
- package/dist/common-Cdj4rLFr.mjs +9 -0
- package/dist/common-Cdj4rLFr.mjs.map +1 -0
- package/dist/common-D2RyWTAZ.cjs +14 -0
- package/dist/common-D2RyWTAZ.cjs.map +1 -0
- package/dist/common-D3fx-IHt.d.cts +16 -0
- package/dist/elysia.cjs +46 -114
- package/dist/elysia.cjs.map +1 -1
- package/dist/elysia.d.cts +37 -36
- package/dist/elysia.d.mts +54 -0
- package/dist/elysia.mjs +48 -0
- package/dist/elysia.mjs.map +1 -0
- package/dist/express.cjs +40 -110
- package/dist/express.cjs.map +1 -1
- package/dist/express.d.cts +21 -20
- package/dist/express.d.mts +32 -0
- package/dist/express.mjs +42 -0
- package/dist/express.mjs.map +1 -0
- package/dist/fastify.cjs +36 -100
- package/dist/fastify.cjs.map +1 -1
- package/dist/fastify.d.cts +15 -14
- package/dist/fastify.d.mts +23 -0
- package/dist/fastify.mjs +36 -0
- package/dist/fastify.mjs.map +1 -0
- package/dist/hono.cjs +31 -108
- package/dist/hono.cjs.map +1 -1
- package/dist/hono.d.cts +11 -10
- package/dist/hono.d.mts +19 -0
- package/dist/hono.mjs +33 -0
- package/dist/hono.mjs.map +1 -0
- package/dist/next.cjs +81 -169
- package/dist/next.cjs.map +1 -1
- package/dist/next.d.cts +32 -29
- package/dist/{next.d.ts → next.d.mts} +32 -29
- package/dist/next.mjs +86 -0
- package/dist/next.mjs.map +1 -0
- package/dist/nuxt.cjs +414 -104
- package/dist/nuxt.cjs.map +1 -1
- package/dist/nuxt.d.cts +538 -12
- package/dist/nuxt.d.mts +545 -0
- package/dist/nuxt.mjs +416 -0
- package/dist/nuxt.mjs.map +1 -0
- package/dist/openapi-BPFL4Hn6.mjs +585 -0
- package/dist/openapi-BPFL4Hn6.mjs.map +1 -0
- package/dist/openapi-BUzfCKi-.cjs +586 -0
- package/dist/openapi-BUzfCKi-.cjs.map +1 -0
- package/dist/spec-utils-C7vlChMD.cjs +278 -0
- package/dist/spec-utils-C7vlChMD.cjs.map +1 -0
- package/dist/spec-utils-Syk4SLCX.mjs +200 -0
- package/dist/spec-utils-Syk4SLCX.mjs.map +1 -0
- package/dist/sveltekit.cjs +87 -188
- package/dist/sveltekit.cjs.map +1 -1
- package/dist/sveltekit.d.cts +24 -22
- package/dist/sveltekit.d.mts +43 -0
- package/dist/sveltekit.mjs +88 -0
- package/dist/sveltekit.mjs.map +1 -0
- package/dist/tanstack-start.cjs +59 -133
- package/dist/tanstack-start.cjs.map +1 -1
- package/dist/tanstack-start.d.cts +19 -14
- package/dist/tanstack-start.d.mts +37 -0
- package/dist/tanstack-start.mjs +60 -0
- package/dist/tanstack-start.mjs.map +1 -0
- package/dist/types-6NFtxov5.d.mts +74 -0
- package/dist/types-DYdFPTkH.d.cts +74 -0
- package/dist/utils-B9NX7OcP.cjs +85 -0
- package/dist/utils-B9NX7OcP.cjs.map +1 -0
- package/dist/utils-Doc_CQNd.mjs +39 -0
- package/dist/utils-Doc_CQNd.mjs.map +1 -0
- package/package.json +28 -27
- package/dist/api.d.ts +0 -237
- package/dist/api.js +0 -4437
- package/dist/api.js.map +0 -1
- package/dist/common-Cuu8bjzK.d.cts +0 -14
- package/dist/common-WHbiInuf.d.ts +0 -14
- package/dist/elysia.d.ts +0 -53
- package/dist/elysia.js +0 -82
- package/dist/elysia.js.map +0 -1
- package/dist/express.d.ts +0 -31
- package/dist/express.js +0 -78
- package/dist/express.js.map +0 -1
- package/dist/fastify.d.ts +0 -22
- package/dist/fastify.js +0 -68
- package/dist/fastify.js.map +0 -1
- package/dist/hono.d.ts +0 -18
- package/dist/hono.js +0 -76
- package/dist/hono.js.map +0 -1
- package/dist/next.js +0 -140
- package/dist/next.js.map +0 -1
- package/dist/nuxt.d.ts +0 -19
- package/dist/nuxt.js +0 -73
- package/dist/nuxt.js.map +0 -1
- package/dist/sveltekit.d.ts +0 -41
- package/dist/sveltekit.js +0 -156
- package/dist/sveltekit.js.map +0 -1
- package/dist/tanstack-start.d.ts +0 -32
- package/dist/tanstack-start.js +0 -104
- package/dist/tanstack-start.js.map +0 -1
- package/dist/types-CU_PWKr9.d.cts +0 -72
- package/dist/types-CU_PWKr9.d.ts +0 -72
package/dist/api.mjs
ADDED
|
@@ -0,0 +1,2745 @@
|
|
|
1
|
+
import { a as isFieldOmitted, c as isOperationIncluded, d as PROCEDURE_ROUTE_PREFIXES, f as getProcedureDef, i as getMetaDescription, l as isProcedureIncluded, o as isFilterKindIncluded, p as mapProcedureArgs, r as getIncludedModels, s as isModelIncluded, u as mayDenyAccess } from "./spec-utils-Syk4SLCX.mjs";
|
|
2
|
+
import { n as log, r as registerCustomSerializers, t as getZodErrorMessage } from "./utils-Doc_CQNd.mjs";
|
|
3
|
+
import { clone, enumerate, lowerCaseFirst, paramCase, safeJSONStringify } from "@zenstackhq/common-helpers";
|
|
4
|
+
import { CoreCrudOperations, ORMError, ORMErrorReason } from "@zenstackhq/orm";
|
|
5
|
+
import { Decimal } from "decimal.js";
|
|
6
|
+
import SuperJSON from "superjson";
|
|
7
|
+
import tsjapi from "ts-japi";
|
|
8
|
+
import { match } from "ts-pattern";
|
|
9
|
+
import UrlPattern from "url-pattern";
|
|
10
|
+
import z from "zod";
|
|
11
|
+
import { fromError } from "zod-validation-error/v4";
|
|
12
|
+
//#region src/api/common/schemas.ts
|
|
13
|
+
const loggerSchema = z.union([z.enum([
|
|
14
|
+
"debug",
|
|
15
|
+
"info",
|
|
16
|
+
"warn",
|
|
17
|
+
"error"
|
|
18
|
+
]).array(), z.function()]);
|
|
19
|
+
const fieldSlicingSchema = z.looseObject({
|
|
20
|
+
includedFilterKinds: z.string().array().optional(),
|
|
21
|
+
excludedFilterKinds: z.string().array().optional()
|
|
22
|
+
});
|
|
23
|
+
const modelSlicingSchema = z.looseObject({
|
|
24
|
+
includedOperations: z.array(z.string()).optional(),
|
|
25
|
+
excludedOperations: z.array(z.string()).optional(),
|
|
26
|
+
fields: z.record(z.string(), fieldSlicingSchema).optional()
|
|
27
|
+
});
|
|
28
|
+
const slicingSchema = z.looseObject({
|
|
29
|
+
includedModels: z.array(z.string()).optional(),
|
|
30
|
+
excludedModels: z.array(z.string()).optional(),
|
|
31
|
+
models: z.record(z.string(), modelSlicingSchema).optional(),
|
|
32
|
+
includedProcedures: z.array(z.string()).optional(),
|
|
33
|
+
excludedProcedures: z.array(z.string()).optional()
|
|
34
|
+
});
|
|
35
|
+
const queryOptionsSchema = z.looseObject({
|
|
36
|
+
omit: z.record(z.string(), z.record(z.string(), z.boolean())).optional(),
|
|
37
|
+
slicing: slicingSchema.optional()
|
|
38
|
+
});
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/api/common/utils.ts
|
|
41
|
+
/**
|
|
42
|
+
* Supports the SuperJSON request payload format used by api handlers
|
|
43
|
+
* `{ meta: { serialization }, ...json }`.
|
|
44
|
+
*/
|
|
45
|
+
async function processSuperJsonRequestPayload(payload) {
|
|
46
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload) || !("meta" in payload)) return {
|
|
47
|
+
result: payload,
|
|
48
|
+
error: void 0
|
|
49
|
+
};
|
|
50
|
+
const { meta, ...rest } = payload;
|
|
51
|
+
if (meta?.serialization) try {
|
|
52
|
+
return {
|
|
53
|
+
result: SuperJSON.deserialize({
|
|
54
|
+
json: rest,
|
|
55
|
+
meta: meta.serialization
|
|
56
|
+
}),
|
|
57
|
+
error: void 0
|
|
58
|
+
};
|
|
59
|
+
} catch (err) {
|
|
60
|
+
return {
|
|
61
|
+
result: void 0,
|
|
62
|
+
error: `failed to deserialize request payload: ${err.message}`
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
result: rest,
|
|
67
|
+
error: void 0
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Supports the SuperJSON query format used by api handlers:
|
|
72
|
+
*/
|
|
73
|
+
function unmarshalQ(value, meta) {
|
|
74
|
+
let parsedValue;
|
|
75
|
+
try {
|
|
76
|
+
parsedValue = JSON.parse(value);
|
|
77
|
+
} catch {
|
|
78
|
+
throw new Error("invalid \"q\" query parameter");
|
|
79
|
+
}
|
|
80
|
+
if (meta) {
|
|
81
|
+
let parsedMeta;
|
|
82
|
+
try {
|
|
83
|
+
parsedMeta = JSON.parse(meta);
|
|
84
|
+
} catch {
|
|
85
|
+
throw new Error("invalid \"meta\" query parameter");
|
|
86
|
+
}
|
|
87
|
+
if (parsedMeta.serialization) return SuperJSON.deserialize({
|
|
88
|
+
json: parsedValue,
|
|
89
|
+
meta: parsedMeta.serialization
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return parsedValue;
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/api/rest/openapi.ts
|
|
96
|
+
function errorResponse(description) {
|
|
97
|
+
return {
|
|
98
|
+
description,
|
|
99
|
+
content: { "application/vnd.api+json": { schema: { $ref: "#/components/schemas/_errorResponse" } } }
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const ERROR_400 = errorResponse("Error occurred while processing the request");
|
|
103
|
+
const ERROR_403 = errorResponse("Forbidden: insufficient permissions to perform this operation");
|
|
104
|
+
const ERROR_404 = errorResponse("Resource not found");
|
|
105
|
+
const ERROR_422 = errorResponse("Operation is unprocessable due to validation errors");
|
|
106
|
+
const SCALAR_STRING_OPS = [
|
|
107
|
+
"$contains",
|
|
108
|
+
"$icontains",
|
|
109
|
+
"$search",
|
|
110
|
+
"$startsWith",
|
|
111
|
+
"$endsWith"
|
|
112
|
+
];
|
|
113
|
+
const SCALAR_COMPARABLE_OPS = [
|
|
114
|
+
"$lt",
|
|
115
|
+
"$lte",
|
|
116
|
+
"$gt",
|
|
117
|
+
"$gte"
|
|
118
|
+
];
|
|
119
|
+
const SCALAR_ARRAY_OPS = [
|
|
120
|
+
"$has",
|
|
121
|
+
"$hasEvery",
|
|
122
|
+
"$hasSome",
|
|
123
|
+
"$isEmpty"
|
|
124
|
+
];
|
|
125
|
+
var RestApiSpecGenerator = class {
|
|
126
|
+
specOptions;
|
|
127
|
+
constructor(handlerOptions) {
|
|
128
|
+
this.handlerOptions = handlerOptions;
|
|
129
|
+
}
|
|
130
|
+
get schema() {
|
|
131
|
+
return this.handlerOptions.schema;
|
|
132
|
+
}
|
|
133
|
+
get modelNameMapping() {
|
|
134
|
+
const mapping = {};
|
|
135
|
+
if (this.handlerOptions.modelNameMapping) for (const [k, v] of Object.entries(this.handlerOptions.modelNameMapping)) mapping[lowerCaseFirst(k)] = v;
|
|
136
|
+
return mapping;
|
|
137
|
+
}
|
|
138
|
+
get queryOptions() {
|
|
139
|
+
return this.handlerOptions?.queryOptions;
|
|
140
|
+
}
|
|
141
|
+
get nestedRoutes() {
|
|
142
|
+
return this.handlerOptions.nestedRoutes ?? false;
|
|
143
|
+
}
|
|
144
|
+
generateSpec(options) {
|
|
145
|
+
this.specOptions = options;
|
|
146
|
+
return {
|
|
147
|
+
openapi: "3.1.0",
|
|
148
|
+
info: {
|
|
149
|
+
title: options?.title ?? "ZenStack Generated API",
|
|
150
|
+
version: options?.version ?? "1.0.0",
|
|
151
|
+
...options?.description && { description: options.description },
|
|
152
|
+
...options?.summary && { summary: options.summary }
|
|
153
|
+
},
|
|
154
|
+
tags: this.generateTags(),
|
|
155
|
+
paths: this.generatePaths(),
|
|
156
|
+
components: {
|
|
157
|
+
schemas: this.generateSchemas(),
|
|
158
|
+
parameters: this.generateSharedParams()
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
generateTags() {
|
|
163
|
+
return getIncludedModels(this.schema, this.queryOptions).map((modelName) => ({
|
|
164
|
+
name: lowerCaseFirst(modelName),
|
|
165
|
+
description: `${modelName} operations`
|
|
166
|
+
}));
|
|
167
|
+
}
|
|
168
|
+
getModelPath(modelName) {
|
|
169
|
+
const lower = lowerCaseFirst(modelName);
|
|
170
|
+
return this.modelNameMapping[lower] ?? lower;
|
|
171
|
+
}
|
|
172
|
+
generatePaths() {
|
|
173
|
+
const paths = {};
|
|
174
|
+
for (const modelName of getIncludedModels(this.schema, this.queryOptions)) {
|
|
175
|
+
const modelDef = this.schema.models[modelName];
|
|
176
|
+
if (this.getIdFields(modelDef).length === 0) continue;
|
|
177
|
+
const modelPath = this.getModelPath(modelName);
|
|
178
|
+
const tag = lowerCaseFirst(modelName);
|
|
179
|
+
const collectionPath = this.buildCollectionPath(modelName, modelDef, tag);
|
|
180
|
+
if (Object.keys(collectionPath).length > 0) paths[`/${modelPath}`] = collectionPath;
|
|
181
|
+
const singlePath = this.buildSinglePath(modelDef, tag);
|
|
182
|
+
if (Object.keys(singlePath).length > 0) paths[`/${modelPath}/{id}`] = singlePath;
|
|
183
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
184
|
+
if (!fieldDef.relation) continue;
|
|
185
|
+
if (!isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
186
|
+
const relModelDef = this.schema.models[fieldDef.type];
|
|
187
|
+
if (!relModelDef) continue;
|
|
188
|
+
if (this.getIdFields(relModelDef).length === 0) continue;
|
|
189
|
+
paths[`/${modelPath}/{id}/${fieldName}`] = this.buildRelatedPath(modelName, fieldName, fieldDef, tag);
|
|
190
|
+
if (this.nestedRoutes && fieldDef.array) {
|
|
191
|
+
const nestedSinglePath = this.buildNestedSinglePath(modelName, fieldName, fieldDef, relModelDef, tag);
|
|
192
|
+
if (Object.keys(nestedSinglePath).length > 0) paths[`/${modelPath}/{id}/${fieldName}/{childId}`] = nestedSinglePath;
|
|
193
|
+
}
|
|
194
|
+
paths[`/${modelPath}/{id}/relationships/${fieldName}`] = this.buildRelationshipPath(modelDef, fieldName, fieldDef, tag);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
if (this.schema.procedures) for (const [procName, procDef] of Object.entries(this.schema.procedures)) {
|
|
198
|
+
if (!isProcedureIncluded(procName, this.queryOptions)) continue;
|
|
199
|
+
if (!!procDef.mutation) paths[`/${PROCEDURE_ROUTE_PREFIXES}/${procName}`] = { post: this.buildProcedureOperation(procName, "post") };
|
|
200
|
+
else paths[`/${PROCEDURE_ROUTE_PREFIXES}/${procName}`] = { get: this.buildProcedureOperation(procName, "get") };
|
|
201
|
+
}
|
|
202
|
+
return paths;
|
|
203
|
+
}
|
|
204
|
+
buildCollectionPath(modelName, modelDef, tag) {
|
|
205
|
+
const filterParams = this.buildFilterParams(modelName, modelDef);
|
|
206
|
+
const listOp = {
|
|
207
|
+
tags: [tag],
|
|
208
|
+
summary: `List ${modelName} resources`,
|
|
209
|
+
operationId: `list${modelName}`,
|
|
210
|
+
parameters: [
|
|
211
|
+
{ $ref: "#/components/parameters/include" },
|
|
212
|
+
{ $ref: "#/components/parameters/sort" },
|
|
213
|
+
{ $ref: "#/components/parameters/pageOffset" },
|
|
214
|
+
{ $ref: "#/components/parameters/pageLimit" },
|
|
215
|
+
...filterParams
|
|
216
|
+
],
|
|
217
|
+
responses: {
|
|
218
|
+
"200": {
|
|
219
|
+
description: `List of ${modelName} resources`,
|
|
220
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}ListResponse` } } }
|
|
221
|
+
},
|
|
222
|
+
"400": ERROR_400
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
const createOp = {
|
|
226
|
+
tags: [tag],
|
|
227
|
+
summary: `Create a ${modelName} resource`,
|
|
228
|
+
operationId: `create${modelName}`,
|
|
229
|
+
requestBody: {
|
|
230
|
+
required: true,
|
|
231
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}CreateRequest` } } }
|
|
232
|
+
},
|
|
233
|
+
responses: {
|
|
234
|
+
"201": {
|
|
235
|
+
description: `Created ${modelName} resource`,
|
|
236
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}Response` } } }
|
|
237
|
+
},
|
|
238
|
+
"400": ERROR_400,
|
|
239
|
+
...mayDenyAccess(modelDef, "create", this.specOptions?.respectAccessPolicies) && { "403": ERROR_403 },
|
|
240
|
+
"422": ERROR_422
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
const result = {};
|
|
244
|
+
if (isOperationIncluded(modelName, "findMany", this.queryOptions)) result["get"] = listOp;
|
|
245
|
+
if (isOperationIncluded(modelName, "create", this.queryOptions)) result["post"] = createOp;
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
buildSinglePath(modelDef, tag) {
|
|
249
|
+
const modelName = modelDef.name;
|
|
250
|
+
const idParam = { $ref: "#/components/parameters/id" };
|
|
251
|
+
const result = {};
|
|
252
|
+
if (isOperationIncluded(modelName, "findUnique", this.queryOptions)) result["get"] = {
|
|
253
|
+
tags: [tag],
|
|
254
|
+
summary: `Get a ${modelName} resource by ID`,
|
|
255
|
+
operationId: `get${modelName}`,
|
|
256
|
+
parameters: [idParam, { $ref: "#/components/parameters/include" }],
|
|
257
|
+
responses: {
|
|
258
|
+
"200": {
|
|
259
|
+
description: `${modelName} resource`,
|
|
260
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}Response` } } }
|
|
261
|
+
},
|
|
262
|
+
"404": ERROR_404
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
if (isOperationIncluded(modelName, "update", this.queryOptions)) result["patch"] = {
|
|
266
|
+
tags: [tag],
|
|
267
|
+
summary: `Update a ${modelName} resource`,
|
|
268
|
+
operationId: `update${modelName}`,
|
|
269
|
+
parameters: [idParam],
|
|
270
|
+
requestBody: {
|
|
271
|
+
required: true,
|
|
272
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}UpdateRequest` } } }
|
|
273
|
+
},
|
|
274
|
+
responses: {
|
|
275
|
+
"200": {
|
|
276
|
+
description: `Updated ${modelName} resource`,
|
|
277
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${modelName}Response` } } }
|
|
278
|
+
},
|
|
279
|
+
"400": ERROR_400,
|
|
280
|
+
...mayDenyAccess(modelDef, "update", this.specOptions?.respectAccessPolicies) && { "403": ERROR_403 },
|
|
281
|
+
"404": ERROR_404,
|
|
282
|
+
"422": ERROR_422
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
if (isOperationIncluded(modelName, "delete", this.queryOptions)) result["delete"] = {
|
|
286
|
+
tags: [tag],
|
|
287
|
+
summary: `Delete a ${modelName} resource`,
|
|
288
|
+
operationId: `delete${modelName}`,
|
|
289
|
+
parameters: [idParam],
|
|
290
|
+
responses: {
|
|
291
|
+
"200": { description: "Deleted successfully" },
|
|
292
|
+
...mayDenyAccess(modelDef, "delete", this.specOptions?.respectAccessPolicies) && { "403": ERROR_403 },
|
|
293
|
+
"404": ERROR_404
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
return result;
|
|
297
|
+
}
|
|
298
|
+
buildRelatedPath(modelName, fieldName, fieldDef, tag) {
|
|
299
|
+
const isCollection = !!fieldDef.array;
|
|
300
|
+
const relModelDef = this.schema.models[fieldDef.type];
|
|
301
|
+
const params = [{ $ref: "#/components/parameters/id" }, { $ref: "#/components/parameters/include" }];
|
|
302
|
+
if (isCollection && relModelDef) params.push({ $ref: "#/components/parameters/sort" }, { $ref: "#/components/parameters/pageOffset" }, { $ref: "#/components/parameters/pageLimit" }, ...this.buildFilterParams(fieldDef.type, relModelDef));
|
|
303
|
+
const pathItem = { get: {
|
|
304
|
+
tags: [tag],
|
|
305
|
+
summary: `Fetch related ${fieldDef.type} for ${modelName}`,
|
|
306
|
+
operationId: `get${modelName}_${fieldName}`,
|
|
307
|
+
parameters: params,
|
|
308
|
+
responses: {
|
|
309
|
+
"200": {
|
|
310
|
+
description: `Related ${fieldDef.type} resource(s)`,
|
|
311
|
+
content: { "application/vnd.api+json": { schema: isCollection ? { $ref: `#/components/schemas/${fieldDef.type}ListResponse` } : { $ref: `#/components/schemas/${fieldDef.type}Response` } } }
|
|
312
|
+
},
|
|
313
|
+
"404": ERROR_404
|
|
314
|
+
}
|
|
315
|
+
} };
|
|
316
|
+
if (this.nestedRoutes && relModelDef) {
|
|
317
|
+
const mayDeny = mayDenyAccess(relModelDef, isCollection ? "create" : "update", this.specOptions?.respectAccessPolicies);
|
|
318
|
+
if (isCollection && isOperationIncluded(fieldDef.type, "create", this.queryOptions)) pathItem["post"] = {
|
|
319
|
+
tags: [tag],
|
|
320
|
+
summary: `Create a nested ${fieldDef.type} under ${modelName}`,
|
|
321
|
+
operationId: `create${modelName}_${fieldName}`,
|
|
322
|
+
parameters: [{ $ref: "#/components/parameters/id" }],
|
|
323
|
+
requestBody: {
|
|
324
|
+
required: true,
|
|
325
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}CreateRequest` } } }
|
|
326
|
+
},
|
|
327
|
+
responses: {
|
|
328
|
+
"201": {
|
|
329
|
+
description: `Created ${fieldDef.type} resource`,
|
|
330
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}Response` } } }
|
|
331
|
+
},
|
|
332
|
+
"400": ERROR_400,
|
|
333
|
+
...mayDeny && { "403": ERROR_403 },
|
|
334
|
+
"422": ERROR_422
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
else if (!isCollection && isOperationIncluded(fieldDef.type, "update", this.queryOptions)) pathItem["patch"] = {
|
|
338
|
+
tags: [tag],
|
|
339
|
+
summary: `Update nested ${fieldDef.type} under ${modelName}`,
|
|
340
|
+
operationId: `update${modelName}_${fieldName}`,
|
|
341
|
+
parameters: [{ $ref: "#/components/parameters/id" }],
|
|
342
|
+
requestBody: {
|
|
343
|
+
required: true,
|
|
344
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}UpdateRequest` } } }
|
|
345
|
+
},
|
|
346
|
+
responses: {
|
|
347
|
+
"200": {
|
|
348
|
+
description: `Updated ${fieldDef.type} resource`,
|
|
349
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}Response` } } }
|
|
350
|
+
},
|
|
351
|
+
"400": ERROR_400,
|
|
352
|
+
...mayDeny && { "403": ERROR_403 },
|
|
353
|
+
"404": ERROR_404,
|
|
354
|
+
"422": ERROR_422
|
|
355
|
+
}
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
return pathItem;
|
|
359
|
+
}
|
|
360
|
+
buildNestedSinglePath(modelName, fieldName, fieldDef, relModelDef, tag) {
|
|
361
|
+
const childIdParam = {
|
|
362
|
+
name: "childId",
|
|
363
|
+
in: "path",
|
|
364
|
+
required: true,
|
|
365
|
+
schema: { type: "string" }
|
|
366
|
+
};
|
|
367
|
+
const idParam = { $ref: "#/components/parameters/id" };
|
|
368
|
+
const mayDenyUpdate = mayDenyAccess(relModelDef, "update", this.specOptions?.respectAccessPolicies);
|
|
369
|
+
const mayDenyDelete = mayDenyAccess(relModelDef, "delete", this.specOptions?.respectAccessPolicies);
|
|
370
|
+
const result = {};
|
|
371
|
+
if (isOperationIncluded(fieldDef.type, "findUnique", this.queryOptions)) result["get"] = {
|
|
372
|
+
tags: [tag],
|
|
373
|
+
summary: `Get a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
374
|
+
operationId: `get${modelName}_${fieldName}_single`,
|
|
375
|
+
parameters: [
|
|
376
|
+
idParam,
|
|
377
|
+
childIdParam,
|
|
378
|
+
{ $ref: "#/components/parameters/include" }
|
|
379
|
+
],
|
|
380
|
+
responses: {
|
|
381
|
+
"200": {
|
|
382
|
+
description: `${fieldDef.type} resource`,
|
|
383
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}Response` } } }
|
|
384
|
+
},
|
|
385
|
+
"404": ERROR_404
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
if (isOperationIncluded(fieldDef.type, "update", this.queryOptions)) result["patch"] = {
|
|
389
|
+
tags: [tag],
|
|
390
|
+
summary: `Update a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
391
|
+
operationId: `update${modelName}_${fieldName}_single`,
|
|
392
|
+
parameters: [idParam, childIdParam],
|
|
393
|
+
requestBody: {
|
|
394
|
+
required: true,
|
|
395
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}UpdateRequest` } } }
|
|
396
|
+
},
|
|
397
|
+
responses: {
|
|
398
|
+
"200": {
|
|
399
|
+
description: `Updated ${fieldDef.type} resource`,
|
|
400
|
+
content: { "application/vnd.api+json": { schema: { $ref: `#/components/schemas/${fieldDef.type}Response` } } }
|
|
401
|
+
},
|
|
402
|
+
"400": ERROR_400,
|
|
403
|
+
...mayDenyUpdate && { "403": ERROR_403 },
|
|
404
|
+
"404": ERROR_404,
|
|
405
|
+
"422": ERROR_422
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
if (isOperationIncluded(fieldDef.type, "delete", this.queryOptions)) result["delete"] = {
|
|
409
|
+
tags: [tag],
|
|
410
|
+
summary: `Delete a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
411
|
+
operationId: `delete${modelName}_${fieldName}_single`,
|
|
412
|
+
parameters: [idParam, childIdParam],
|
|
413
|
+
responses: {
|
|
414
|
+
"200": { description: "Deleted successfully" },
|
|
415
|
+
...mayDenyDelete && { "403": ERROR_403 },
|
|
416
|
+
"404": ERROR_404
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
return result;
|
|
420
|
+
}
|
|
421
|
+
buildRelationshipPath(modelDef, fieldName, fieldDef, tag) {
|
|
422
|
+
const modelName = modelDef.name;
|
|
423
|
+
const isCollection = !!fieldDef.array;
|
|
424
|
+
const idParam = { $ref: "#/components/parameters/id" };
|
|
425
|
+
const relSchemaRef = isCollection ? { $ref: "#/components/schemas/_toManyRelationshipWithLinks" } : { $ref: "#/components/schemas/_toOneRelationshipWithLinks" };
|
|
426
|
+
const relRequestRef = isCollection ? { $ref: "#/components/schemas/_toManyRelationshipRequest" } : { $ref: "#/components/schemas/_toOneRelationshipRequest" };
|
|
427
|
+
const mayDeny = mayDenyAccess(modelDef, "update", this.specOptions?.respectAccessPolicies);
|
|
428
|
+
const pathItem = {
|
|
429
|
+
get: {
|
|
430
|
+
tags: [tag],
|
|
431
|
+
summary: `Fetch ${fieldName} relationship`,
|
|
432
|
+
operationId: `get${modelName}_relationships_${fieldName}`,
|
|
433
|
+
parameters: [idParam],
|
|
434
|
+
responses: {
|
|
435
|
+
"200": {
|
|
436
|
+
description: `${fieldName} relationship`,
|
|
437
|
+
content: { "application/vnd.api+json": { schema: relSchemaRef } }
|
|
438
|
+
},
|
|
439
|
+
"404": ERROR_404
|
|
440
|
+
}
|
|
441
|
+
},
|
|
442
|
+
put: {
|
|
443
|
+
tags: [tag],
|
|
444
|
+
summary: `Replace ${fieldName} relationship`,
|
|
445
|
+
operationId: `put${modelName}_relationships_${fieldName}`,
|
|
446
|
+
parameters: [idParam],
|
|
447
|
+
requestBody: {
|
|
448
|
+
required: true,
|
|
449
|
+
content: { "application/vnd.api+json": { schema: relRequestRef } }
|
|
450
|
+
},
|
|
451
|
+
responses: {
|
|
452
|
+
"200": { description: "Relationship updated" },
|
|
453
|
+
"400": ERROR_400,
|
|
454
|
+
...mayDeny && { "403": ERROR_403 }
|
|
455
|
+
}
|
|
456
|
+
},
|
|
457
|
+
patch: {
|
|
458
|
+
tags: [tag],
|
|
459
|
+
summary: `Update ${fieldName} relationship`,
|
|
460
|
+
operationId: `patch${modelName}_relationships_${fieldName}`,
|
|
461
|
+
parameters: [idParam],
|
|
462
|
+
requestBody: {
|
|
463
|
+
required: true,
|
|
464
|
+
content: { "application/vnd.api+json": { schema: relRequestRef } }
|
|
465
|
+
},
|
|
466
|
+
responses: {
|
|
467
|
+
"200": { description: "Relationship updated" },
|
|
468
|
+
"400": ERROR_400,
|
|
469
|
+
...mayDeny && { "403": ERROR_403 }
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
if (isCollection) pathItem["post"] = {
|
|
474
|
+
tags: [tag],
|
|
475
|
+
summary: `Add to ${fieldName} collection relationship`,
|
|
476
|
+
operationId: `post${modelName}_relationships_${fieldName}`,
|
|
477
|
+
parameters: [idParam],
|
|
478
|
+
requestBody: {
|
|
479
|
+
required: true,
|
|
480
|
+
content: { "application/vnd.api+json": { schema: { $ref: "#/components/schemas/_toManyRelationshipRequest" } } }
|
|
481
|
+
},
|
|
482
|
+
responses: {
|
|
483
|
+
"200": { description: "Added to relationship collection" },
|
|
484
|
+
"400": ERROR_400,
|
|
485
|
+
...mayDeny && { "403": ERROR_403 }
|
|
486
|
+
}
|
|
487
|
+
};
|
|
488
|
+
return pathItem;
|
|
489
|
+
}
|
|
490
|
+
buildProcedureOperation(procName, method) {
|
|
491
|
+
const op = {
|
|
492
|
+
tags: ["$procs"],
|
|
493
|
+
summary: `Execute procedure ${procName}`,
|
|
494
|
+
operationId: `proc_${procName}`,
|
|
495
|
+
responses: {
|
|
496
|
+
"200": { description: `Result of ${procName}` },
|
|
497
|
+
"400": ERROR_400
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
if (method === "get") op["parameters"] = [{
|
|
501
|
+
name: "q",
|
|
502
|
+
in: "query",
|
|
503
|
+
description: "Procedure arguments as JSON",
|
|
504
|
+
schema: { type: "string" }
|
|
505
|
+
}];
|
|
506
|
+
else op["requestBody"] = { content: { "application/json": { schema: { type: "object" } } } };
|
|
507
|
+
return op;
|
|
508
|
+
}
|
|
509
|
+
buildFilterParams(modelName, modelDef) {
|
|
510
|
+
const params = [];
|
|
511
|
+
const idFieldNames = new Set(modelDef.idFields);
|
|
512
|
+
if (isFilterKindIncluded(modelName, "id", "Equality", this.queryOptions)) params.push({
|
|
513
|
+
name: "filter[id]",
|
|
514
|
+
in: "query",
|
|
515
|
+
schema: { type: "string" },
|
|
516
|
+
description: `Filter by ${modelName} ID`
|
|
517
|
+
});
|
|
518
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
519
|
+
if (fieldDef.relation) continue;
|
|
520
|
+
if (idFieldNames.has(fieldName)) continue;
|
|
521
|
+
const type = fieldDef.type;
|
|
522
|
+
if (isFilterKindIncluded(modelName, fieldName, "Equality", this.queryOptions)) params.push({
|
|
523
|
+
name: `filter[${fieldName}]`,
|
|
524
|
+
in: "query",
|
|
525
|
+
schema: { type: "string" },
|
|
526
|
+
description: `Filter by ${fieldName}`
|
|
527
|
+
});
|
|
528
|
+
if (type === "String" && isFilterKindIncluded(modelName, fieldName, "Like", this.queryOptions)) for (const op of SCALAR_STRING_OPS) params.push({
|
|
529
|
+
name: `filter[${fieldName}][${op}]`,
|
|
530
|
+
in: "query",
|
|
531
|
+
schema: { type: "string" }
|
|
532
|
+
});
|
|
533
|
+
else if ((type === "Int" || type === "Float" || type === "BigInt" || type === "Decimal" || type === "DateTime") && isFilterKindIncluded(modelName, fieldName, "Range", this.queryOptions)) for (const op of SCALAR_COMPARABLE_OPS) params.push({
|
|
534
|
+
name: `filter[${fieldName}][${op}]`,
|
|
535
|
+
in: "query",
|
|
536
|
+
schema: { type: "string" }
|
|
537
|
+
});
|
|
538
|
+
if (fieldDef.array && isFilterKindIncluded(modelName, fieldName, "List", this.queryOptions)) for (const op of SCALAR_ARRAY_OPS) params.push({
|
|
539
|
+
name: `filter[${fieldName}][${op}]`,
|
|
540
|
+
in: "query",
|
|
541
|
+
schema: { type: "string" }
|
|
542
|
+
});
|
|
543
|
+
}
|
|
544
|
+
return params;
|
|
545
|
+
}
|
|
546
|
+
generateSchemas() {
|
|
547
|
+
const schemas = {};
|
|
548
|
+
Object.assign(schemas, this.buildSharedSchemas());
|
|
549
|
+
if (this.schema.enums) for (const [_enumName, enumDef] of Object.entries(this.schema.enums)) schemas[_enumName] = this.buildEnumSchema(enumDef);
|
|
550
|
+
if (this.schema.typeDefs) for (const [typeName, typeDef] of Object.entries(this.schema.typeDefs)) schemas[typeName] = this.buildTypeDefSchema(typeDef);
|
|
551
|
+
for (const modelName of getIncludedModels(this.schema, this.queryOptions)) {
|
|
552
|
+
const modelDef = this.schema.models[modelName];
|
|
553
|
+
if (this.getIdFields(modelDef).length === 0) continue;
|
|
554
|
+
schemas[modelName] = this.buildModelReadSchema(modelName, modelDef);
|
|
555
|
+
schemas[`${modelName}CreateRequest`] = this.buildCreateRequestSchema(modelName, modelDef);
|
|
556
|
+
schemas[`${modelName}UpdateRequest`] = this.buildUpdateRequestSchema(modelDef);
|
|
557
|
+
schemas[`${modelName}Response`] = this.buildModelResponseSchema(modelName);
|
|
558
|
+
schemas[`${modelName}ListResponse`] = this.buildModelListResponseSchema(modelName);
|
|
559
|
+
}
|
|
560
|
+
return schemas;
|
|
561
|
+
}
|
|
562
|
+
buildSharedSchemas() {
|
|
563
|
+
const nullableString = { oneOf: [{ type: "string" }, { type: "null" }] };
|
|
564
|
+
return {
|
|
565
|
+
_jsonapi: {
|
|
566
|
+
type: "object",
|
|
567
|
+
properties: {
|
|
568
|
+
version: { type: "string" },
|
|
569
|
+
meta: { type: "object" }
|
|
570
|
+
}
|
|
571
|
+
},
|
|
572
|
+
_meta: {
|
|
573
|
+
type: "object",
|
|
574
|
+
additionalProperties: true
|
|
575
|
+
},
|
|
576
|
+
_links: {
|
|
577
|
+
type: "object",
|
|
578
|
+
properties: {
|
|
579
|
+
self: { type: "string" },
|
|
580
|
+
related: { type: "string" }
|
|
581
|
+
}
|
|
582
|
+
},
|
|
583
|
+
_pagination: {
|
|
584
|
+
type: "object",
|
|
585
|
+
properties: {
|
|
586
|
+
first: nullableString,
|
|
587
|
+
last: nullableString,
|
|
588
|
+
prev: nullableString,
|
|
589
|
+
next: nullableString
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
_errors: {
|
|
593
|
+
type: "array",
|
|
594
|
+
items: {
|
|
595
|
+
type: "object",
|
|
596
|
+
properties: {
|
|
597
|
+
status: { type: "integer" },
|
|
598
|
+
code: { type: "string" },
|
|
599
|
+
title: { type: "string" },
|
|
600
|
+
detail: { type: "string" }
|
|
601
|
+
},
|
|
602
|
+
required: ["status", "title"]
|
|
603
|
+
}
|
|
604
|
+
},
|
|
605
|
+
_errorResponse: {
|
|
606
|
+
type: "object",
|
|
607
|
+
properties: { errors: { $ref: "#/components/schemas/_errors" } },
|
|
608
|
+
required: ["errors"]
|
|
609
|
+
},
|
|
610
|
+
_resourceIdentifier: {
|
|
611
|
+
type: "object",
|
|
612
|
+
properties: {
|
|
613
|
+
type: { type: "string" },
|
|
614
|
+
id: { type: "string" }
|
|
615
|
+
},
|
|
616
|
+
required: ["type", "id"]
|
|
617
|
+
},
|
|
618
|
+
_resource: {
|
|
619
|
+
type: "object",
|
|
620
|
+
properties: {
|
|
621
|
+
type: { type: "string" },
|
|
622
|
+
id: { type: "string" },
|
|
623
|
+
attributes: { type: "object" },
|
|
624
|
+
relationships: { type: "object" },
|
|
625
|
+
links: { $ref: "#/components/schemas/_links" },
|
|
626
|
+
meta: { $ref: "#/components/schemas/_meta" }
|
|
627
|
+
},
|
|
628
|
+
required: ["type", "id"]
|
|
629
|
+
},
|
|
630
|
+
_relationLinks: {
|
|
631
|
+
type: "object",
|
|
632
|
+
properties: {
|
|
633
|
+
self: { type: "string" },
|
|
634
|
+
related: { type: "string" }
|
|
635
|
+
}
|
|
636
|
+
},
|
|
637
|
+
_pagedRelationLinks: {
|
|
638
|
+
type: "object",
|
|
639
|
+
allOf: [{ $ref: "#/components/schemas/_relationLinks" }, { $ref: "#/components/schemas/_pagination" }]
|
|
640
|
+
},
|
|
641
|
+
_toOneRelationship: {
|
|
642
|
+
type: "object",
|
|
643
|
+
properties: { data: { oneOf: [{ $ref: "#/components/schemas/_resourceIdentifier" }, { type: "null" }] } }
|
|
644
|
+
},
|
|
645
|
+
_toManyRelationship: {
|
|
646
|
+
type: "object",
|
|
647
|
+
properties: { data: {
|
|
648
|
+
type: "array",
|
|
649
|
+
items: { $ref: "#/components/schemas/_resourceIdentifier" }
|
|
650
|
+
} }
|
|
651
|
+
},
|
|
652
|
+
_toOneRelationshipWithLinks: {
|
|
653
|
+
type: "object",
|
|
654
|
+
allOf: [{ $ref: "#/components/schemas/_toOneRelationship" }, { properties: { links: { $ref: "#/components/schemas/_relationLinks" } } }]
|
|
655
|
+
},
|
|
656
|
+
_toManyRelationshipWithLinks: {
|
|
657
|
+
type: "object",
|
|
658
|
+
allOf: [{ $ref: "#/components/schemas/_toManyRelationship" }, { properties: { links: { $ref: "#/components/schemas/_pagedRelationLinks" } } }]
|
|
659
|
+
},
|
|
660
|
+
_toManyRelationshipRequest: {
|
|
661
|
+
type: "object",
|
|
662
|
+
properties: { data: {
|
|
663
|
+
type: "array",
|
|
664
|
+
items: { $ref: "#/components/schemas/_resourceIdentifier" }
|
|
665
|
+
} },
|
|
666
|
+
required: ["data"]
|
|
667
|
+
},
|
|
668
|
+
_toOneRelationshipRequest: {
|
|
669
|
+
type: "object",
|
|
670
|
+
properties: { data: { oneOf: [{ $ref: "#/components/schemas/_resourceIdentifier" }, { type: "null" }] } },
|
|
671
|
+
required: ["data"]
|
|
672
|
+
},
|
|
673
|
+
_toManyRelationshipResponse: {
|
|
674
|
+
type: "object",
|
|
675
|
+
properties: {
|
|
676
|
+
data: {
|
|
677
|
+
type: "array",
|
|
678
|
+
items: { $ref: "#/components/schemas/_resourceIdentifier" }
|
|
679
|
+
},
|
|
680
|
+
links: { $ref: "#/components/schemas/_pagedRelationLinks" },
|
|
681
|
+
meta: { $ref: "#/components/schemas/_meta" }
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
_toOneRelationshipResponse: {
|
|
685
|
+
type: "object",
|
|
686
|
+
properties: {
|
|
687
|
+
data: { oneOf: [{ $ref: "#/components/schemas/_resourceIdentifier" }, { type: "null" }] },
|
|
688
|
+
links: { $ref: "#/components/schemas/_relationLinks" },
|
|
689
|
+
meta: { $ref: "#/components/schemas/_meta" }
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
buildEnumSchema(enumDef) {
|
|
695
|
+
return {
|
|
696
|
+
type: "string",
|
|
697
|
+
enum: Object.values(enumDef.values)
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
buildTypeDefSchema(typeDef) {
|
|
701
|
+
const properties = {};
|
|
702
|
+
const required = [];
|
|
703
|
+
for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) {
|
|
704
|
+
properties[fieldName] = this.fieldToSchema(fieldDef);
|
|
705
|
+
if (!fieldDef.optional && !fieldDef.array) required.push(fieldName);
|
|
706
|
+
}
|
|
707
|
+
const result = {
|
|
708
|
+
type: "object",
|
|
709
|
+
properties
|
|
710
|
+
};
|
|
711
|
+
if (required.length > 0) result.required = required;
|
|
712
|
+
return result;
|
|
713
|
+
}
|
|
714
|
+
buildModelReadSchema(modelName, modelDef) {
|
|
715
|
+
const attrProperties = {};
|
|
716
|
+
const attrRequired = [];
|
|
717
|
+
const relProperties = {};
|
|
718
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
719
|
+
if (fieldDef.omit) continue;
|
|
720
|
+
if (isFieldOmitted(modelName, fieldName, this.queryOptions)) continue;
|
|
721
|
+
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
722
|
+
if (fieldDef.relation) {
|
|
723
|
+
const relRef = fieldDef.array ? { $ref: "#/components/schemas/_toManyRelationshipWithLinks" } : { $ref: "#/components/schemas/_toOneRelationshipWithLinks" };
|
|
724
|
+
relProperties[fieldName] = fieldDef.optional ? { oneOf: [{ type: "null" }, relRef] } : relRef;
|
|
725
|
+
} else {
|
|
726
|
+
const schema = this.fieldToSchema(fieldDef);
|
|
727
|
+
const fieldDescription = getMetaDescription(fieldDef.attributes);
|
|
728
|
+
if (fieldDescription && !("$ref" in schema)) schema.description = fieldDescription;
|
|
729
|
+
attrProperties[fieldName] = schema;
|
|
730
|
+
if (!fieldDef.optional && !fieldDef.array) attrRequired.push(fieldName);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
const properties = {};
|
|
734
|
+
if (Object.keys(attrProperties).length > 0) {
|
|
735
|
+
const attrSchema = {
|
|
736
|
+
type: "object",
|
|
737
|
+
properties: attrProperties
|
|
738
|
+
};
|
|
739
|
+
if (attrRequired.length > 0) attrSchema.required = attrRequired;
|
|
740
|
+
properties["attributes"] = attrSchema;
|
|
741
|
+
}
|
|
742
|
+
if (Object.keys(relProperties).length > 0) properties["relationships"] = {
|
|
743
|
+
type: "object",
|
|
744
|
+
properties: relProperties
|
|
745
|
+
};
|
|
746
|
+
const result = {
|
|
747
|
+
type: "object",
|
|
748
|
+
properties
|
|
749
|
+
};
|
|
750
|
+
const description = getMetaDescription(modelDef.attributes);
|
|
751
|
+
if (description) result.description = description;
|
|
752
|
+
return result;
|
|
753
|
+
}
|
|
754
|
+
buildCreateRequestSchema(_modelName, modelDef) {
|
|
755
|
+
const idFieldNames = new Set(modelDef.idFields);
|
|
756
|
+
const attributes = {};
|
|
757
|
+
const attrRequired = [];
|
|
758
|
+
const relationships = {};
|
|
759
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
760
|
+
if (fieldDef.updatedAt) continue;
|
|
761
|
+
if (fieldDef.foreignKeyFor) continue;
|
|
762
|
+
if (idFieldNames.has(fieldName) && fieldDef.default !== void 0) continue;
|
|
763
|
+
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
764
|
+
if (fieldDef.relation) relationships[fieldName] = fieldDef.array ? {
|
|
765
|
+
type: "object",
|
|
766
|
+
properties: { data: {
|
|
767
|
+
type: "array",
|
|
768
|
+
items: { $ref: "#/components/schemas/_resourceIdentifier" }
|
|
769
|
+
} }
|
|
770
|
+
} : {
|
|
771
|
+
type: "object",
|
|
772
|
+
properties: { data: { $ref: "#/components/schemas/_resourceIdentifier" } }
|
|
773
|
+
};
|
|
774
|
+
else {
|
|
775
|
+
attributes[fieldName] = this.fieldToSchema(fieldDef);
|
|
776
|
+
if (!fieldDef.optional && fieldDef.default === void 0 && !fieldDef.array) attrRequired.push(fieldName);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
const dataProperties = { type: { type: "string" } };
|
|
780
|
+
if (Object.keys(attributes).length > 0) {
|
|
781
|
+
const attrSchema = {
|
|
782
|
+
type: "object",
|
|
783
|
+
properties: attributes
|
|
784
|
+
};
|
|
785
|
+
if (attrRequired.length > 0) attrSchema.required = attrRequired;
|
|
786
|
+
dataProperties["attributes"] = attrSchema;
|
|
787
|
+
}
|
|
788
|
+
if (Object.keys(relationships).length > 0) dataProperties["relationships"] = {
|
|
789
|
+
type: "object",
|
|
790
|
+
properties: relationships
|
|
791
|
+
};
|
|
792
|
+
return {
|
|
793
|
+
type: "object",
|
|
794
|
+
properties: { data: {
|
|
795
|
+
type: "object",
|
|
796
|
+
properties: dataProperties,
|
|
797
|
+
required: ["type"]
|
|
798
|
+
} },
|
|
799
|
+
required: ["data"]
|
|
800
|
+
};
|
|
801
|
+
}
|
|
802
|
+
buildUpdateRequestSchema(modelDef) {
|
|
803
|
+
const attributes = {};
|
|
804
|
+
const relationships = {};
|
|
805
|
+
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
806
|
+
if (fieldDef.updatedAt) continue;
|
|
807
|
+
if (fieldDef.foreignKeyFor) continue;
|
|
808
|
+
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
809
|
+
if (fieldDef.relation) relationships[fieldName] = fieldDef.array ? {
|
|
810
|
+
type: "object",
|
|
811
|
+
properties: { data: {
|
|
812
|
+
type: "array",
|
|
813
|
+
items: { $ref: "#/components/schemas/_resourceIdentifier" }
|
|
814
|
+
} }
|
|
815
|
+
} : {
|
|
816
|
+
type: "object",
|
|
817
|
+
properties: { data: { $ref: "#/components/schemas/_resourceIdentifier" } }
|
|
818
|
+
};
|
|
819
|
+
else attributes[fieldName] = this.fieldToSchema(fieldDef);
|
|
820
|
+
}
|
|
821
|
+
const dataProperties = {
|
|
822
|
+
type: { type: "string" },
|
|
823
|
+
id: { type: "string" }
|
|
824
|
+
};
|
|
825
|
+
if (Object.keys(attributes).length > 0) dataProperties["attributes"] = {
|
|
826
|
+
type: "object",
|
|
827
|
+
properties: attributes
|
|
828
|
+
};
|
|
829
|
+
if (Object.keys(relationships).length > 0) dataProperties["relationships"] = {
|
|
830
|
+
type: "object",
|
|
831
|
+
properties: relationships
|
|
832
|
+
};
|
|
833
|
+
return {
|
|
834
|
+
type: "object",
|
|
835
|
+
properties: { data: {
|
|
836
|
+
type: "object",
|
|
837
|
+
properties: dataProperties,
|
|
838
|
+
required: ["type", "id"]
|
|
839
|
+
} },
|
|
840
|
+
required: ["data"]
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
buildModelResponseSchema(modelName) {
|
|
844
|
+
return {
|
|
845
|
+
type: "object",
|
|
846
|
+
properties: {
|
|
847
|
+
jsonapi: { $ref: "#/components/schemas/_jsonapi" },
|
|
848
|
+
data: { allOf: [{ $ref: `#/components/schemas/${modelName}` }, { $ref: "#/components/schemas/_resource" }] },
|
|
849
|
+
meta: { $ref: "#/components/schemas/_meta" }
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
}
|
|
853
|
+
buildModelListResponseSchema(modelName) {
|
|
854
|
+
return {
|
|
855
|
+
type: "object",
|
|
856
|
+
properties: {
|
|
857
|
+
jsonapi: { $ref: "#/components/schemas/_jsonapi" },
|
|
858
|
+
data: {
|
|
859
|
+
type: "array",
|
|
860
|
+
items: { allOf: [{ $ref: `#/components/schemas/${modelName}` }, { $ref: "#/components/schemas/_resource" }] }
|
|
861
|
+
},
|
|
862
|
+
links: { allOf: [{ $ref: "#/components/schemas/_pagination" }, { $ref: "#/components/schemas/_links" }] },
|
|
863
|
+
meta: { $ref: "#/components/schemas/_meta" }
|
|
864
|
+
}
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
generateSharedParams() {
|
|
868
|
+
return {
|
|
869
|
+
id: {
|
|
870
|
+
name: "id",
|
|
871
|
+
in: "path",
|
|
872
|
+
required: true,
|
|
873
|
+
schema: { type: "string" },
|
|
874
|
+
description: "Resource ID"
|
|
875
|
+
},
|
|
876
|
+
include: {
|
|
877
|
+
name: "include",
|
|
878
|
+
in: "query",
|
|
879
|
+
schema: { type: "string" },
|
|
880
|
+
description: "Comma-separated list of relationships to include"
|
|
881
|
+
},
|
|
882
|
+
sort: {
|
|
883
|
+
name: "sort",
|
|
884
|
+
in: "query",
|
|
885
|
+
schema: { type: "string" },
|
|
886
|
+
description: "Comma-separated list of fields to sort by. Prefix with - for descending"
|
|
887
|
+
},
|
|
888
|
+
pageOffset: {
|
|
889
|
+
name: "page[offset]",
|
|
890
|
+
in: "query",
|
|
891
|
+
schema: {
|
|
892
|
+
type: "integer",
|
|
893
|
+
minimum: 0
|
|
894
|
+
},
|
|
895
|
+
description: "Page offset"
|
|
896
|
+
},
|
|
897
|
+
pageLimit: {
|
|
898
|
+
name: "page[limit]",
|
|
899
|
+
in: "query",
|
|
900
|
+
schema: {
|
|
901
|
+
type: "integer",
|
|
902
|
+
minimum: 1
|
|
903
|
+
},
|
|
904
|
+
description: "Page limit"
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
fieldToSchema(fieldDef) {
|
|
909
|
+
const baseSchema = this.typeToSchema(fieldDef.type);
|
|
910
|
+
if (fieldDef.array) return {
|
|
911
|
+
type: "array",
|
|
912
|
+
items: baseSchema
|
|
913
|
+
};
|
|
914
|
+
if (fieldDef.optional) return { oneOf: [baseSchema, { type: "null" }] };
|
|
915
|
+
return baseSchema;
|
|
916
|
+
}
|
|
917
|
+
typeToSchema(type) {
|
|
918
|
+
switch (type) {
|
|
919
|
+
case "String": return { type: "string" };
|
|
920
|
+
case "Int":
|
|
921
|
+
case "BigInt": return { type: "integer" };
|
|
922
|
+
case "Float": return { type: "number" };
|
|
923
|
+
case "Decimal": return { oneOf: [{ type: "number" }, { type: "string" }] };
|
|
924
|
+
case "Boolean": return { type: "boolean" };
|
|
925
|
+
case "DateTime": return {
|
|
926
|
+
type: "string",
|
|
927
|
+
format: "date-time"
|
|
928
|
+
};
|
|
929
|
+
case "Bytes": return {
|
|
930
|
+
type: "string",
|
|
931
|
+
format: "byte"
|
|
932
|
+
};
|
|
933
|
+
case "Json":
|
|
934
|
+
case "Unsupported": return {};
|
|
935
|
+
default: return { $ref: `#/components/schemas/${type}` };
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
getIdFields(modelDef) {
|
|
939
|
+
return modelDef.idFields.map((name) => modelDef.fields[name]).filter((f) => f !== void 0);
|
|
940
|
+
}
|
|
941
|
+
};
|
|
942
|
+
//#endregion
|
|
943
|
+
//#region src/api/rest/index.ts
|
|
944
|
+
var UrlPatterns = /* @__PURE__ */ function(UrlPatterns) {
|
|
945
|
+
UrlPatterns["SINGLE"] = "single";
|
|
946
|
+
UrlPatterns["NESTED_SINGLE"] = "nestedSingle";
|
|
947
|
+
UrlPatterns["FETCH_RELATIONSHIP"] = "fetchRelationship";
|
|
948
|
+
UrlPatterns["RELATIONSHIP"] = "relationship";
|
|
949
|
+
UrlPatterns["COLLECTION"] = "collection";
|
|
950
|
+
return UrlPatterns;
|
|
951
|
+
}(UrlPatterns || {});
|
|
952
|
+
var InvalidValueError = class extends Error {
|
|
953
|
+
constructor(message) {
|
|
954
|
+
super(message);
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
const DEFAULT_PAGE_SIZE = 100;
|
|
958
|
+
const FilterOperations = [
|
|
959
|
+
"lt",
|
|
960
|
+
"lte",
|
|
961
|
+
"gt",
|
|
962
|
+
"gte",
|
|
963
|
+
"between",
|
|
964
|
+
"contains",
|
|
965
|
+
"icontains",
|
|
966
|
+
"search",
|
|
967
|
+
"startsWith",
|
|
968
|
+
"endsWith",
|
|
969
|
+
"has",
|
|
970
|
+
"hasEvery",
|
|
971
|
+
"hasSome",
|
|
972
|
+
"isEmpty"
|
|
973
|
+
];
|
|
974
|
+
const DEFAULT_ID_DIVIDER = "_";
|
|
975
|
+
registerCustomSerializers();
|
|
976
|
+
/**
|
|
977
|
+
* RESTful-style API request handler (compliant with JSON:API)
|
|
978
|
+
*/
|
|
979
|
+
var RestApiHandler = class {
|
|
980
|
+
serializers = /* @__PURE__ */ new Map();
|
|
981
|
+
errors = {
|
|
982
|
+
unsupportedModel: {
|
|
983
|
+
status: 404,
|
|
984
|
+
title: "Unsupported model type",
|
|
985
|
+
detail: "The model type is not supported"
|
|
986
|
+
},
|
|
987
|
+
unsupportedRelationship: {
|
|
988
|
+
status: 400,
|
|
989
|
+
title: "Unsupported relationship",
|
|
990
|
+
detail: "The relationship is not supported"
|
|
991
|
+
},
|
|
992
|
+
invalidPath: {
|
|
993
|
+
status: 400,
|
|
994
|
+
title: "The request path is invalid"
|
|
995
|
+
},
|
|
996
|
+
invalidVerb: {
|
|
997
|
+
status: 400,
|
|
998
|
+
title: "The HTTP verb is not supported"
|
|
999
|
+
},
|
|
1000
|
+
notFound: {
|
|
1001
|
+
status: 404,
|
|
1002
|
+
title: "Resource not found"
|
|
1003
|
+
},
|
|
1004
|
+
noId: {
|
|
1005
|
+
status: 400,
|
|
1006
|
+
title: "Model without an ID field is not supported"
|
|
1007
|
+
},
|
|
1008
|
+
invalidId: {
|
|
1009
|
+
status: 400,
|
|
1010
|
+
title: "Resource ID is invalid"
|
|
1011
|
+
},
|
|
1012
|
+
invalidPayload: {
|
|
1013
|
+
status: 400,
|
|
1014
|
+
title: "Invalid payload"
|
|
1015
|
+
},
|
|
1016
|
+
invalidRelationData: {
|
|
1017
|
+
status: 400,
|
|
1018
|
+
title: "Invalid relation data",
|
|
1019
|
+
detail: "Invalid relationship data"
|
|
1020
|
+
},
|
|
1021
|
+
invalidRelation: {
|
|
1022
|
+
status: 400,
|
|
1023
|
+
title: "Invalid relation",
|
|
1024
|
+
detail: "Invalid relationship"
|
|
1025
|
+
},
|
|
1026
|
+
invalidFilter: {
|
|
1027
|
+
status: 400,
|
|
1028
|
+
title: "Invalid filter"
|
|
1029
|
+
},
|
|
1030
|
+
invalidSort: {
|
|
1031
|
+
status: 400,
|
|
1032
|
+
title: "Invalid sort"
|
|
1033
|
+
},
|
|
1034
|
+
invalidValue: {
|
|
1035
|
+
status: 400,
|
|
1036
|
+
title: "Invalid value for type"
|
|
1037
|
+
},
|
|
1038
|
+
duplicatedFieldsParameter: {
|
|
1039
|
+
status: 400,
|
|
1040
|
+
title: "Fields Parameter Duplicated"
|
|
1041
|
+
},
|
|
1042
|
+
forbidden: {
|
|
1043
|
+
status: 403,
|
|
1044
|
+
title: "Operation is forbidden"
|
|
1045
|
+
},
|
|
1046
|
+
validationError: {
|
|
1047
|
+
status: 422,
|
|
1048
|
+
title: "Operation is unprocessable due to validation errors"
|
|
1049
|
+
},
|
|
1050
|
+
queryError: {
|
|
1051
|
+
status: 400,
|
|
1052
|
+
title: "Error occurred while executing the query"
|
|
1053
|
+
},
|
|
1054
|
+
unknownError: {
|
|
1055
|
+
status: 500,
|
|
1056
|
+
title: "Unknown error"
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
filterParamPattern = /* @__PURE__ */ new RegExp(/^filter(?<match>(\[[^[\]]+\])+)$/);
|
|
1060
|
+
createUpdatePayloadSchema = z.object({
|
|
1061
|
+
data: z.object({
|
|
1062
|
+
type: z.string(),
|
|
1063
|
+
attributes: z.object({}).passthrough().optional(),
|
|
1064
|
+
relationships: z.record(z.string(), z.object({ data: z.union([z.object({
|
|
1065
|
+
type: z.string(),
|
|
1066
|
+
id: z.union([z.string(), z.number()])
|
|
1067
|
+
}), z.array(z.object({
|
|
1068
|
+
type: z.string(),
|
|
1069
|
+
id: z.union([z.string(), z.number()])
|
|
1070
|
+
}))]) })).optional()
|
|
1071
|
+
}),
|
|
1072
|
+
meta: z.object({}).passthrough().optional()
|
|
1073
|
+
}).strict();
|
|
1074
|
+
updateSingleRelationSchema = z.object({ data: z.object({
|
|
1075
|
+
type: z.string(),
|
|
1076
|
+
id: z.union([z.string(), z.number()])
|
|
1077
|
+
}).nullable() });
|
|
1078
|
+
updateCollectionRelationSchema = z.object({ data: z.array(z.object({
|
|
1079
|
+
type: z.string(),
|
|
1080
|
+
id: z.union([z.string(), z.number()])
|
|
1081
|
+
})) });
|
|
1082
|
+
upsertMetaSchema = z.object({ meta: z.object({
|
|
1083
|
+
operation: z.literal("upsert"),
|
|
1084
|
+
matchFields: z.array(z.string()).min(1)
|
|
1085
|
+
}) });
|
|
1086
|
+
typeMap = {};
|
|
1087
|
+
idDivider;
|
|
1088
|
+
urlPatternMap;
|
|
1089
|
+
modelNameMapping;
|
|
1090
|
+
reverseModelNameMapping;
|
|
1091
|
+
externalIdMapping;
|
|
1092
|
+
nestedRoutes;
|
|
1093
|
+
constructor(options) {
|
|
1094
|
+
this.options = options;
|
|
1095
|
+
this.validateOptions(options);
|
|
1096
|
+
this.idDivider = options.idDivider ?? DEFAULT_ID_DIVIDER;
|
|
1097
|
+
const segmentCharset = options.urlSegmentCharset ?? "a-zA-Z0-9-_~ %";
|
|
1098
|
+
this.modelNameMapping = options.modelNameMapping ?? {};
|
|
1099
|
+
this.modelNameMapping = Object.fromEntries(Object.entries(this.modelNameMapping).map(([k, v]) => [lowerCaseFirst(k), v]));
|
|
1100
|
+
this.reverseModelNameMapping = Object.fromEntries(Object.entries(this.modelNameMapping).map(([k, v]) => [v, k]));
|
|
1101
|
+
this.externalIdMapping = options.externalIdMapping ?? {};
|
|
1102
|
+
this.externalIdMapping = Object.fromEntries(Object.entries(this.externalIdMapping).map(([k, v]) => [lowerCaseFirst(k), v]));
|
|
1103
|
+
this.nestedRoutes = options.nestedRoutes ?? false;
|
|
1104
|
+
this.urlPatternMap = this.buildUrlPatternMap(segmentCharset);
|
|
1105
|
+
this.buildTypeMap();
|
|
1106
|
+
this.buildSerializers();
|
|
1107
|
+
}
|
|
1108
|
+
validateOptions(options) {
|
|
1109
|
+
const parseResult = z.strictObject({
|
|
1110
|
+
schema: z.object(),
|
|
1111
|
+
log: loggerSchema.optional(),
|
|
1112
|
+
endpoint: z.string().min(1),
|
|
1113
|
+
pageSize: z.union([z.number().int().positive(), z.literal(Infinity)]).optional(),
|
|
1114
|
+
idDivider: z.string().min(1).optional(),
|
|
1115
|
+
urlSegmentCharset: z.string().min(1).optional(),
|
|
1116
|
+
modelNameMapping: z.record(z.string(), z.string()).optional(),
|
|
1117
|
+
externalIdMapping: z.record(z.string(), z.string()).optional(),
|
|
1118
|
+
queryOptions: queryOptionsSchema.optional(),
|
|
1119
|
+
nestedRoutes: z.boolean().optional()
|
|
1120
|
+
}).safeParse(options);
|
|
1121
|
+
if (!parseResult.success) throw new Error(`Invalid options: ${fromError(parseResult.error)}`);
|
|
1122
|
+
}
|
|
1123
|
+
get schema() {
|
|
1124
|
+
return this.options.schema;
|
|
1125
|
+
}
|
|
1126
|
+
get log() {
|
|
1127
|
+
return this.options.log;
|
|
1128
|
+
}
|
|
1129
|
+
buildUrlPatternMap(urlSegmentNameCharset) {
|
|
1130
|
+
const options = { segmentValueCharset: urlSegmentNameCharset };
|
|
1131
|
+
const buildPath = (segments) => {
|
|
1132
|
+
return "/" + segments.join("/");
|
|
1133
|
+
};
|
|
1134
|
+
return {
|
|
1135
|
+
[UrlPatterns.SINGLE]: new UrlPattern(buildPath([":type", ":id"]), options),
|
|
1136
|
+
[UrlPatterns.NESTED_SINGLE]: new UrlPattern(buildPath([
|
|
1137
|
+
":type",
|
|
1138
|
+
":id",
|
|
1139
|
+
":relationship",
|
|
1140
|
+
":childId"
|
|
1141
|
+
]), options),
|
|
1142
|
+
[UrlPatterns.FETCH_RELATIONSHIP]: new UrlPattern(buildPath([
|
|
1143
|
+
":type",
|
|
1144
|
+
":id",
|
|
1145
|
+
":relationship"
|
|
1146
|
+
]), options),
|
|
1147
|
+
[UrlPatterns.RELATIONSHIP]: new UrlPattern(buildPath([
|
|
1148
|
+
":type",
|
|
1149
|
+
":id",
|
|
1150
|
+
"relationships",
|
|
1151
|
+
":relationship"
|
|
1152
|
+
]), options),
|
|
1153
|
+
[UrlPatterns.COLLECTION]: new UrlPattern(buildPath([":type"]), options)
|
|
1154
|
+
};
|
|
1155
|
+
}
|
|
1156
|
+
mapModelName(modelName) {
|
|
1157
|
+
return this.modelNameMapping[modelName] ?? modelName;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Resolves child model type and reverse relation from a parent relation name.
|
|
1161
|
+
* e.g. given parentType='user', parentRelation='posts', returns { childType:'post', reverseRelation:'author' }
|
|
1162
|
+
*/
|
|
1163
|
+
resolveNestedRelation(parentType, parentRelation) {
|
|
1164
|
+
const parentInfo = this.getModelInfo(parentType);
|
|
1165
|
+
if (!parentInfo) return void 0;
|
|
1166
|
+
const field = this.schema.models[parentInfo.name]?.fields[parentRelation];
|
|
1167
|
+
if (!field?.relation) return void 0;
|
|
1168
|
+
const reverseRelation = field.relation.opposite;
|
|
1169
|
+
if (!reverseRelation) return void 0;
|
|
1170
|
+
return {
|
|
1171
|
+
childType: lowerCaseFirst(field.type),
|
|
1172
|
+
reverseRelation,
|
|
1173
|
+
isCollection: !!field.array
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
mergeFilters(left, right) {
|
|
1177
|
+
if (!left) return right;
|
|
1178
|
+
if (!right) return left;
|
|
1179
|
+
return { AND: [left, right] };
|
|
1180
|
+
}
|
|
1181
|
+
/**
|
|
1182
|
+
* Builds a WHERE filter for the child model that constrains results to those belonging to the given parent.
|
|
1183
|
+
* @param parentType lowercased parent model name
|
|
1184
|
+
* @param parentId parent resource ID string
|
|
1185
|
+
* @param parentRelation relation field name on the parent model (e.g. 'posts')
|
|
1186
|
+
*/
|
|
1187
|
+
buildNestedParentFilter(parentType, parentId, parentRelation) {
|
|
1188
|
+
const parentInfo = this.getModelInfo(parentType);
|
|
1189
|
+
if (!parentInfo) return {
|
|
1190
|
+
filter: void 0,
|
|
1191
|
+
error: this.makeUnsupportedModelError(parentType)
|
|
1192
|
+
};
|
|
1193
|
+
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
1194
|
+
if (!resolved) return {
|
|
1195
|
+
filter: void 0,
|
|
1196
|
+
error: this.makeError("invalidPath", `invalid nested route: cannot resolve relation "${parentType}.${parentRelation}"`)
|
|
1197
|
+
};
|
|
1198
|
+
const { reverseRelation } = resolved;
|
|
1199
|
+
const childInfo = this.getModelInfo(resolved.childType);
|
|
1200
|
+
if (!childInfo) return {
|
|
1201
|
+
filter: void 0,
|
|
1202
|
+
error: this.makeUnsupportedModelError(resolved.childType)
|
|
1203
|
+
};
|
|
1204
|
+
return {
|
|
1205
|
+
filter: childInfo.relationships[reverseRelation]?.isCollection ? { [reverseRelation]: { some: this.makeIdFilter(parentInfo.idFields, parentId, false) } } : { [reverseRelation]: { is: this.makeIdFilter(parentInfo.idFields, parentId, false) } },
|
|
1206
|
+
error: void 0
|
|
1207
|
+
};
|
|
1208
|
+
}
|
|
1209
|
+
matchUrlPattern(path, routeType) {
|
|
1210
|
+
const pattern = this.urlPatternMap[routeType];
|
|
1211
|
+
if (!pattern) throw new InvalidValueError(`Unknown route type: ${routeType}`);
|
|
1212
|
+
const match = pattern.match(path);
|
|
1213
|
+
if (!match) return;
|
|
1214
|
+
if (match.type in this.modelNameMapping) throw new InvalidValueError(`use the mapped model name: ${this.modelNameMapping[match.type]} and not ${match.type}`);
|
|
1215
|
+
if (match.type in this.reverseModelNameMapping) match.type = this.reverseModelNameMapping[match.type];
|
|
1216
|
+
return match;
|
|
1217
|
+
}
|
|
1218
|
+
async handleRequest({ client, method, path, query, requestBody }) {
|
|
1219
|
+
method = method.toUpperCase();
|
|
1220
|
+
if (!path.startsWith("/")) path = "/" + path;
|
|
1221
|
+
try {
|
|
1222
|
+
if (path.startsWith("/$procs/")) {
|
|
1223
|
+
const proc = path.split("/")[2];
|
|
1224
|
+
return await this.processProcedureRequest({
|
|
1225
|
+
client,
|
|
1226
|
+
method,
|
|
1227
|
+
proc,
|
|
1228
|
+
query,
|
|
1229
|
+
requestBody
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
switch (method) {
|
|
1233
|
+
case "GET": {
|
|
1234
|
+
let match = this.matchUrlPattern(path, UrlPatterns.SINGLE);
|
|
1235
|
+
if (match) return await this.processSingleRead(client, match.type, match.id, query);
|
|
1236
|
+
match = this.matchUrlPattern(path, UrlPatterns.FETCH_RELATIONSHIP);
|
|
1237
|
+
if (match) return await this.processFetchRelated(client, match.type, match.id, match.relationship, query);
|
|
1238
|
+
match = this.matchUrlPattern(path, UrlPatterns.RELATIONSHIP);
|
|
1239
|
+
if (match) return await this.processReadRelationship(client, match.type, match.id, match.relationship, query);
|
|
1240
|
+
match = this.matchUrlPattern(path, UrlPatterns.NESTED_SINGLE);
|
|
1241
|
+
if (match && this.nestedRoutes && this.resolveNestedRelation(match.type, match.relationship)?.isCollection) return await this.processNestedSingleRead(client, match.type, match.id, match.relationship, match.childId, query);
|
|
1242
|
+
match = this.matchUrlPattern(path, UrlPatterns.COLLECTION);
|
|
1243
|
+
if (match) return await this.processCollectionRead(client, match.type, query);
|
|
1244
|
+
return this.makeError("invalidPath");
|
|
1245
|
+
}
|
|
1246
|
+
case "POST": {
|
|
1247
|
+
if (!requestBody) return this.makeError("invalidPayload");
|
|
1248
|
+
const nestedMatch = this.matchUrlPattern(path, UrlPatterns.FETCH_RELATIONSHIP);
|
|
1249
|
+
if (nestedMatch && this.nestedRoutes && this.resolveNestedRelation(nestedMatch.type, nestedMatch.relationship)?.isCollection) return await this.processNestedCreate(client, nestedMatch.type, nestedMatch.id, nestedMatch.relationship, query, requestBody);
|
|
1250
|
+
let match = this.matchUrlPattern(path, UrlPatterns.COLLECTION);
|
|
1251
|
+
if (match) {
|
|
1252
|
+
const body = requestBody;
|
|
1253
|
+
if (this.upsertMetaSchema.safeParse(body).success) return await this.processUpsert(client, match.type, query, requestBody);
|
|
1254
|
+
else return await this.processCreate(client, match.type, query, requestBody);
|
|
1255
|
+
}
|
|
1256
|
+
match = this.matchUrlPattern(path, UrlPatterns.RELATIONSHIP);
|
|
1257
|
+
if (match) return await this.processRelationshipCRUD(client, "create", match.type, match.id, match.relationship, query, requestBody);
|
|
1258
|
+
return this.makeError("invalidPath");
|
|
1259
|
+
}
|
|
1260
|
+
case "PUT":
|
|
1261
|
+
case "PATCH": {
|
|
1262
|
+
if (!requestBody) return this.makeError("invalidPayload");
|
|
1263
|
+
let match = this.matchUrlPattern(path, UrlPatterns.RELATIONSHIP);
|
|
1264
|
+
if (match) return await this.processRelationshipCRUD(client, "update", match.type, match.id, match.relationship, query, requestBody);
|
|
1265
|
+
const nestedToOnePatchMatch = this.matchUrlPattern(path, UrlPatterns.FETCH_RELATIONSHIP);
|
|
1266
|
+
if (nestedToOnePatchMatch && this.nestedRoutes && this.resolveNestedRelation(nestedToOnePatchMatch.type, nestedToOnePatchMatch.relationship) && !this.resolveNestedRelation(nestedToOnePatchMatch.type, nestedToOnePatchMatch.relationship)?.isCollection) return await this.processNestedUpdate(client, nestedToOnePatchMatch.type, nestedToOnePatchMatch.id, nestedToOnePatchMatch.relationship, void 0, query, requestBody);
|
|
1267
|
+
const nestedPatchMatch = this.matchUrlPattern(path, UrlPatterns.NESTED_SINGLE);
|
|
1268
|
+
if (nestedPatchMatch && this.nestedRoutes && this.resolveNestedRelation(nestedPatchMatch.type, nestedPatchMatch.relationship)?.isCollection) return await this.processNestedUpdate(client, nestedPatchMatch.type, nestedPatchMatch.id, nestedPatchMatch.relationship, nestedPatchMatch.childId, query, requestBody);
|
|
1269
|
+
match = this.matchUrlPattern(path, UrlPatterns.SINGLE);
|
|
1270
|
+
if (match) return await this.processUpdate(client, match.type, match.id, query, requestBody);
|
|
1271
|
+
return this.makeError("invalidPath");
|
|
1272
|
+
}
|
|
1273
|
+
case "DELETE": {
|
|
1274
|
+
let match = this.matchUrlPattern(path, UrlPatterns.RELATIONSHIP);
|
|
1275
|
+
if (match) return await this.processRelationshipCRUD(client, "delete", match.type, match.id, match.relationship, query, requestBody);
|
|
1276
|
+
const nestedDeleteMatch = this.matchUrlPattern(path, UrlPatterns.NESTED_SINGLE);
|
|
1277
|
+
if (nestedDeleteMatch && this.nestedRoutes && this.resolveNestedRelation(nestedDeleteMatch.type, nestedDeleteMatch.relationship)?.isCollection) return await this.processNestedDelete(client, nestedDeleteMatch.type, nestedDeleteMatch.id, nestedDeleteMatch.relationship, nestedDeleteMatch.childId);
|
|
1278
|
+
match = this.matchUrlPattern(path, UrlPatterns.SINGLE);
|
|
1279
|
+
if (match) return await this.processDelete(client, match.type, match.id);
|
|
1280
|
+
return this.makeError("invalidPath");
|
|
1281
|
+
}
|
|
1282
|
+
default: return this.makeError("invalidPath");
|
|
1283
|
+
}
|
|
1284
|
+
} catch (err) {
|
|
1285
|
+
if (err instanceof InvalidValueError) return this.makeError("invalidValue", err.message);
|
|
1286
|
+
else if (err instanceof ORMError) return this.handleORMError(err);
|
|
1287
|
+
else return this.handleGenericError(err);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
handleGenericError(err) {
|
|
1291
|
+
const resp = this.makeError("unknownError", err instanceof Error ? `${err.message}` : "Unknown error");
|
|
1292
|
+
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
1293
|
+
return resp;
|
|
1294
|
+
}
|
|
1295
|
+
async processProcedureRequest({ client, method, proc, query, requestBody }) {
|
|
1296
|
+
if (!proc) return this.makeProcBadInputErrorResponse("missing procedure name");
|
|
1297
|
+
const procDef = getProcedureDef(this.schema, proc);
|
|
1298
|
+
if (!procDef) return this.makeProcBadInputErrorResponse(`unknown procedure: ${proc}`);
|
|
1299
|
+
if (!!procDef.mutation) {
|
|
1300
|
+
if (method !== "POST") return this.makeProcBadInputErrorResponse("invalid request method, only POST is supported");
|
|
1301
|
+
} else if (method !== "GET") return this.makeProcBadInputErrorResponse("invalid request method, only GET is supported");
|
|
1302
|
+
const { result: processedArgsPayload, error } = await processSuperJsonRequestPayload(method === "POST" ? requestBody : query);
|
|
1303
|
+
if (error) return this.makeProcBadInputErrorResponse(error);
|
|
1304
|
+
let procInput;
|
|
1305
|
+
try {
|
|
1306
|
+
procInput = mapProcedureArgs(procDef, processedArgsPayload);
|
|
1307
|
+
} catch (err) {
|
|
1308
|
+
return this.makeProcBadInputErrorResponse(err instanceof Error ? err.message : "invalid procedure arguments");
|
|
1309
|
+
}
|
|
1310
|
+
try {
|
|
1311
|
+
log(this.log, "debug", () => `handling "$procs.${proc}" request`);
|
|
1312
|
+
const clientResult = await client.$procs?.[proc](procInput);
|
|
1313
|
+
const toSerialize = this.toPlainObject(clientResult);
|
|
1314
|
+
const { json, meta } = SuperJSON.serialize(toSerialize);
|
|
1315
|
+
const responseBody = { data: json };
|
|
1316
|
+
if (meta) responseBody.meta = { serialization: meta };
|
|
1317
|
+
return {
|
|
1318
|
+
status: 200,
|
|
1319
|
+
body: responseBody
|
|
1320
|
+
};
|
|
1321
|
+
} catch (err) {
|
|
1322
|
+
log(this.log, "error", `error occurred when handling "$procs.${proc}" request`, err);
|
|
1323
|
+
if (err instanceof ORMError) throw err;
|
|
1324
|
+
return this.makeProcGenericErrorResponse(err);
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
makeProcBadInputErrorResponse(message) {
|
|
1328
|
+
const resp = this.makeError("invalidPayload", message, 400);
|
|
1329
|
+
log(this.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}`);
|
|
1330
|
+
return resp;
|
|
1331
|
+
}
|
|
1332
|
+
makeProcGenericErrorResponse(err) {
|
|
1333
|
+
const message = err instanceof Error ? err.message : "unknown error";
|
|
1334
|
+
const resp = this.makeError("unknownError", message, 500);
|
|
1335
|
+
log(this.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
1336
|
+
return resp;
|
|
1337
|
+
}
|
|
1338
|
+
/**
|
|
1339
|
+
* Builds the ORM `args` object (include, select) shared by single-read operations.
|
|
1340
|
+
* Returns the args to pass to findUnique/findFirst and the resolved `include` list for serialization,
|
|
1341
|
+
* or an error response if query params are invalid.
|
|
1342
|
+
*/
|
|
1343
|
+
buildSingleReadArgs(type, query) {
|
|
1344
|
+
const args = {};
|
|
1345
|
+
this.includeRelationshipIds(type, args, "include");
|
|
1346
|
+
let include;
|
|
1347
|
+
if (query?.["include"]) {
|
|
1348
|
+
const { select, error, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
1349
|
+
if (error) return {
|
|
1350
|
+
args,
|
|
1351
|
+
include,
|
|
1352
|
+
error
|
|
1353
|
+
};
|
|
1354
|
+
if (select) args.include = {
|
|
1355
|
+
...args.include,
|
|
1356
|
+
...select
|
|
1357
|
+
};
|
|
1358
|
+
include = allIncludes;
|
|
1359
|
+
}
|
|
1360
|
+
const { select, error } = this.buildPartialSelect(type, query);
|
|
1361
|
+
if (error) return {
|
|
1362
|
+
args,
|
|
1363
|
+
include,
|
|
1364
|
+
error
|
|
1365
|
+
};
|
|
1366
|
+
if (select) {
|
|
1367
|
+
args.select = {
|
|
1368
|
+
...select,
|
|
1369
|
+
...args.select
|
|
1370
|
+
};
|
|
1371
|
+
if (args.include) {
|
|
1372
|
+
args.select = {
|
|
1373
|
+
...args.select,
|
|
1374
|
+
...args.include
|
|
1375
|
+
};
|
|
1376
|
+
args.include = void 0;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
return {
|
|
1380
|
+
args,
|
|
1381
|
+
include
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
async processSingleRead(client, type, resourceId, query) {
|
|
1385
|
+
const typeInfo = this.getModelInfo(type);
|
|
1386
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1387
|
+
const { args, include, error } = this.buildSingleReadArgs(type, query);
|
|
1388
|
+
if (error) return error;
|
|
1389
|
+
args.where = this.makeIdFilter(typeInfo.idFields, resourceId);
|
|
1390
|
+
const entity = await client[type].findUnique(args);
|
|
1391
|
+
if (entity) return {
|
|
1392
|
+
status: 200,
|
|
1393
|
+
body: await this.serializeItems(type, entity, { include })
|
|
1394
|
+
};
|
|
1395
|
+
else return this.makeError("notFound");
|
|
1396
|
+
}
|
|
1397
|
+
async processFetchRelated(client, type, resourceId, relationship, query) {
|
|
1398
|
+
const typeInfo = this.getModelInfo(type);
|
|
1399
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1400
|
+
const relationInfo = typeInfo.relationships[relationship];
|
|
1401
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
1402
|
+
let select;
|
|
1403
|
+
let include;
|
|
1404
|
+
if (query?.["include"]) {
|
|
1405
|
+
const { select: relationSelect, error, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
1406
|
+
if (error) return error;
|
|
1407
|
+
include = allIncludes.filter((i) => i.startsWith(`${relationship}.`)).map((i) => i.substring(`${relationship}.`.length));
|
|
1408
|
+
select = relationSelect;
|
|
1409
|
+
}
|
|
1410
|
+
if (!select) {
|
|
1411
|
+
const { select: partialFields, error } = this.buildPartialSelect(lowerCaseFirst(relationInfo.type), query);
|
|
1412
|
+
if (error) return error;
|
|
1413
|
+
select = partialFields ? { [relationship]: { select: { ...partialFields } } } : { [relationship]: true };
|
|
1414
|
+
}
|
|
1415
|
+
const args = {
|
|
1416
|
+
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
1417
|
+
select
|
|
1418
|
+
};
|
|
1419
|
+
if (relationInfo.isCollection) {
|
|
1420
|
+
const error = this.injectRelationQuery(relationInfo.type, select, relationship, query);
|
|
1421
|
+
if (error) return error;
|
|
1422
|
+
}
|
|
1423
|
+
const entity = await client[type].findUnique(args);
|
|
1424
|
+
let paginator;
|
|
1425
|
+
if (entity?._count?.[relationship] !== void 0) {
|
|
1426
|
+
const total = entity?._count?.[relationship];
|
|
1427
|
+
const url = this.makeNormalizedUrl(`/${type}/${resourceId}/${relationship}`, query);
|
|
1428
|
+
const { offset, limit } = this.getPagination(query);
|
|
1429
|
+
paginator = this.makePaginator(url, offset, limit, total);
|
|
1430
|
+
}
|
|
1431
|
+
if (entity?.[relationship]) {
|
|
1432
|
+
const mappedType = this.mapModelName(type);
|
|
1433
|
+
return {
|
|
1434
|
+
status: 200,
|
|
1435
|
+
body: await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
1436
|
+
linkers: {
|
|
1437
|
+
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/${relationship}`)),
|
|
1438
|
+
paginator
|
|
1439
|
+
},
|
|
1440
|
+
include
|
|
1441
|
+
})
|
|
1442
|
+
};
|
|
1443
|
+
} else return this.makeError("notFound");
|
|
1444
|
+
}
|
|
1445
|
+
async processReadRelationship(client, type, resourceId, relationship, query) {
|
|
1446
|
+
const typeInfo = this.getModelInfo(type);
|
|
1447
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1448
|
+
const relationInfo = typeInfo.relationships[relationship];
|
|
1449
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
1450
|
+
const args = {
|
|
1451
|
+
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
1452
|
+
select: this.makeIdSelect(typeInfo.idFields)
|
|
1453
|
+
};
|
|
1454
|
+
args.select = {
|
|
1455
|
+
...args.select,
|
|
1456
|
+
[relationship]: { select: this.makeIdSelect(relationInfo.idFields) }
|
|
1457
|
+
};
|
|
1458
|
+
let paginator;
|
|
1459
|
+
if (relationInfo.isCollection) {
|
|
1460
|
+
const error = this.injectRelationQuery(relationInfo.type, args.select, relationship, query);
|
|
1461
|
+
if (error) return error;
|
|
1462
|
+
}
|
|
1463
|
+
const entity = await client[type].findUnique(args);
|
|
1464
|
+
const mappedType = this.mapModelName(type);
|
|
1465
|
+
if (entity?._count?.[relationship] !== void 0) {
|
|
1466
|
+
const total = entity?._count?.[relationship];
|
|
1467
|
+
const url = this.makeNormalizedUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`, query);
|
|
1468
|
+
const { offset, limit } = this.getPagination(query);
|
|
1469
|
+
paginator = this.makePaginator(url, offset, limit, total);
|
|
1470
|
+
}
|
|
1471
|
+
if (entity?.[relationship]) return {
|
|
1472
|
+
status: 200,
|
|
1473
|
+
body: await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
1474
|
+
linkers: {
|
|
1475
|
+
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`)),
|
|
1476
|
+
paginator
|
|
1477
|
+
},
|
|
1478
|
+
onlyIdentifier: true
|
|
1479
|
+
})
|
|
1480
|
+
};
|
|
1481
|
+
else return this.makeError("notFound");
|
|
1482
|
+
}
|
|
1483
|
+
async processCollectionRead(client, type, query) {
|
|
1484
|
+
if (!this.getModelInfo(type)) return this.makeUnsupportedModelError(type);
|
|
1485
|
+
const args = {};
|
|
1486
|
+
const { filter, error: filterError } = this.buildFilter(type, query);
|
|
1487
|
+
if (filterError) return filterError;
|
|
1488
|
+
if (filter) args.where = filter;
|
|
1489
|
+
const { sort, error: sortError } = this.buildSort(type, query);
|
|
1490
|
+
if (sortError) return sortError;
|
|
1491
|
+
if (sort) args.orderBy = sort;
|
|
1492
|
+
this.includeRelationshipIds(type, args, "include");
|
|
1493
|
+
let include;
|
|
1494
|
+
if (query?.["include"]) {
|
|
1495
|
+
const { select, error, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
1496
|
+
if (error) return error;
|
|
1497
|
+
if (select) args.include = {
|
|
1498
|
+
...args.include,
|
|
1499
|
+
...select
|
|
1500
|
+
};
|
|
1501
|
+
include = allIncludes;
|
|
1502
|
+
}
|
|
1503
|
+
const { select, error } = this.buildPartialSelect(type, query);
|
|
1504
|
+
if (error) return error;
|
|
1505
|
+
if (select) {
|
|
1506
|
+
args.select = {
|
|
1507
|
+
...select,
|
|
1508
|
+
...args.select
|
|
1509
|
+
};
|
|
1510
|
+
if (args.include) {
|
|
1511
|
+
args.select = {
|
|
1512
|
+
...args.select,
|
|
1513
|
+
...args.include
|
|
1514
|
+
};
|
|
1515
|
+
args.include = void 0;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
const { offset, limit } = this.getPagination(query);
|
|
1519
|
+
if (offset > 0) args.skip = offset;
|
|
1520
|
+
if (limit === Infinity) {
|
|
1521
|
+
const entities = await client[type].findMany(args);
|
|
1522
|
+
const mappedType = this.mapModelName(type);
|
|
1523
|
+
const body = await this.serializeItems(type, entities, {
|
|
1524
|
+
include,
|
|
1525
|
+
linkers: { document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}`)) }
|
|
1526
|
+
});
|
|
1527
|
+
const total = entities.length;
|
|
1528
|
+
body.meta = this.addTotalCountToMeta(body.meta, total);
|
|
1529
|
+
return {
|
|
1530
|
+
status: 200,
|
|
1531
|
+
body
|
|
1532
|
+
};
|
|
1533
|
+
} else {
|
|
1534
|
+
args.take = limit;
|
|
1535
|
+
const [entities, count] = await Promise.all([client[type].findMany(args), client[type].count({ where: args.where ?? {} })]);
|
|
1536
|
+
const total = count;
|
|
1537
|
+
const mappedType = this.mapModelName(type);
|
|
1538
|
+
const url = this.makeNormalizedUrl(`/${mappedType}`, query);
|
|
1539
|
+
const options = {
|
|
1540
|
+
include,
|
|
1541
|
+
linkers: {
|
|
1542
|
+
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}`)),
|
|
1543
|
+
paginator: this.makePaginator(url, offset, limit, total)
|
|
1544
|
+
}
|
|
1545
|
+
};
|
|
1546
|
+
const body = await this.serializeItems(type, entities, options);
|
|
1547
|
+
body.meta = this.addTotalCountToMeta(body.meta, total);
|
|
1548
|
+
return {
|
|
1549
|
+
status: 200,
|
|
1550
|
+
body
|
|
1551
|
+
};
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Builds link URL for a nested resource using parent type, parent ID, relation name, and optional child ID.
|
|
1556
|
+
* Uses the parent model name mapping for the parent segment; the relation name is used as-is.
|
|
1557
|
+
*/
|
|
1558
|
+
makeNestedLinkUrl(parentType, parentId, parentRelation, childId) {
|
|
1559
|
+
const base = `/${this.mapModelName(parentType)}/${parentId}/${parentRelation}`;
|
|
1560
|
+
return childId ? `${base}/${childId}` : base;
|
|
1561
|
+
}
|
|
1562
|
+
async processNestedSingleRead(client, parentType, parentId, parentRelation, childId, query) {
|
|
1563
|
+
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
1564
|
+
if (!resolved) return this.makeError("invalidPath");
|
|
1565
|
+
const { filter: nestedFilter, error: nestedError } = this.buildNestedParentFilter(parentType, parentId, parentRelation);
|
|
1566
|
+
if (nestedError) return nestedError;
|
|
1567
|
+
const childType = resolved.childType;
|
|
1568
|
+
const typeInfo = this.getModelInfo(childType);
|
|
1569
|
+
const { args, include, error } = this.buildSingleReadArgs(childType, query);
|
|
1570
|
+
if (error) return error;
|
|
1571
|
+
args.where = this.mergeFilters(this.makeIdFilter(typeInfo.idFields, childId), nestedFilter);
|
|
1572
|
+
const entity = await client[childType].findFirst(args);
|
|
1573
|
+
if (!entity) return this.makeError("notFound");
|
|
1574
|
+
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation, childId));
|
|
1575
|
+
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
1576
|
+
return {
|
|
1577
|
+
status: 200,
|
|
1578
|
+
body: await this.serializeItems(childType, entity, {
|
|
1579
|
+
include,
|
|
1580
|
+
linkers: {
|
|
1581
|
+
document: nestedLinker,
|
|
1582
|
+
resource: nestedLinker
|
|
1583
|
+
}
|
|
1584
|
+
})
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
async processNestedCreate(client, parentType, parentId, parentRelation, _query, requestBody) {
|
|
1588
|
+
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
1589
|
+
if (!resolved) return this.makeError("invalidPath");
|
|
1590
|
+
const parentInfo = this.getModelInfo(parentType);
|
|
1591
|
+
const childType = resolved.childType;
|
|
1592
|
+
const childInfo = this.getModelInfo(childType);
|
|
1593
|
+
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
1594
|
+
if (error) return error;
|
|
1595
|
+
const createData = { ...attributes };
|
|
1596
|
+
if (relationships) for (const [key, data] of Object.entries(relationships)) {
|
|
1597
|
+
if (!data?.data) return this.makeError("invalidRelationData");
|
|
1598
|
+
if (key === resolved.reverseRelation) return this.makeError("invalidPayload", `Relation "${key}" is controlled by the parent route and cannot be set in the request payload`);
|
|
1599
|
+
const relationInfo = childInfo.relationships[key];
|
|
1600
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(childType, key, 400);
|
|
1601
|
+
if (relationInfo.isCollection) createData[key] = { connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id)) };
|
|
1602
|
+
else {
|
|
1603
|
+
if (typeof data.data !== "object") return this.makeError("invalidRelationData");
|
|
1604
|
+
createData[key] = { connect: this.makeIdConnect(relationInfo.idFields, data.data.id) };
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
if (Object.values(childInfo.fields).filter((f) => f.foreignKeyFor?.includes(resolved.reverseRelation)).some((f) => Object.prototype.hasOwnProperty.call(createData, f.name))) return this.makeError("invalidPayload", `Relation "${resolved.reverseRelation}" is controlled by the parent route and cannot be set in the request payload`);
|
|
1608
|
+
await client[parentType].update({
|
|
1609
|
+
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
1610
|
+
data: { [parentRelation]: { create: createData } }
|
|
1611
|
+
});
|
|
1612
|
+
const { filter: nestedFilter, error: filterError } = this.buildNestedParentFilter(parentType, parentId, parentRelation);
|
|
1613
|
+
if (filterError) return filterError;
|
|
1614
|
+
const fetchArgs = { where: nestedFilter };
|
|
1615
|
+
this.includeRelationshipIds(childType, fetchArgs, "include");
|
|
1616
|
+
if (childInfo.idFields[0]) fetchArgs.orderBy = { [childInfo.idFields[0].name]: "desc" };
|
|
1617
|
+
const entity = await client[childType].findFirst(fetchArgs);
|
|
1618
|
+
if (!entity) return this.makeError("notFound");
|
|
1619
|
+
const collectionPath = this.makeNestedLinkUrl(parentType, parentId, parentRelation);
|
|
1620
|
+
const resourceLinker = new tsjapi.Linker((item) => this.makeLinkUrl(`${collectionPath}/${this.getId(childInfo.name, item)}`));
|
|
1621
|
+
return {
|
|
1622
|
+
status: 201,
|
|
1623
|
+
body: await this.serializeItems(childType, entity, { linkers: {
|
|
1624
|
+
document: resourceLinker,
|
|
1625
|
+
resource: resourceLinker
|
|
1626
|
+
} })
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
/**
|
|
1630
|
+
* Builds the ORM `data` payload for a nested update, shared by both to-many (childId present)
|
|
1631
|
+
* and to-one (childId absent) variants. Returns either `{ updateData }` or `{ error }`.
|
|
1632
|
+
*/
|
|
1633
|
+
buildNestedUpdatePayload(childType, typeInfo, rev, requestBody) {
|
|
1634
|
+
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
1635
|
+
if (error) return { error };
|
|
1636
|
+
const updateData = { ...attributes };
|
|
1637
|
+
if (relationships && Object.prototype.hasOwnProperty.call(relationships, rev)) return { error: this.makeError("invalidPayload", `Relation "${rev}" cannot be changed via a nested route`) };
|
|
1638
|
+
if (Object.values(typeInfo.fields).filter((f) => f.foreignKeyFor?.includes(rev)).some((f) => Object.prototype.hasOwnProperty.call(updateData, f.name))) return { error: this.makeError("invalidPayload", `Relation "${rev}" cannot be changed via a nested route`) };
|
|
1639
|
+
if (relationships) for (const [key, data] of Object.entries(relationships)) {
|
|
1640
|
+
if (!data?.data) return { error: this.makeError("invalidRelationData") };
|
|
1641
|
+
const relationInfo = typeInfo.relationships[key];
|
|
1642
|
+
if (!relationInfo) return { error: this.makeUnsupportedRelationshipError(childType, key, 400) };
|
|
1643
|
+
if (relationInfo.isCollection) updateData[key] = { set: enumerate(data.data).map((item) => ({ [this.makeDefaultIdKey(relationInfo.idFields)]: item.id })) };
|
|
1644
|
+
else {
|
|
1645
|
+
if (typeof data.data !== "object") return { error: this.makeError("invalidRelationData") };
|
|
1646
|
+
updateData[key] = { connect: { [this.makeDefaultIdKey(relationInfo.idFields)]: data.data.id } };
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
return { updateData };
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Handles PATCH /:type/:id/:relationship/:childId (to-many) and
|
|
1653
|
+
* PATCH /:type/:id/:relationship (to-one, childId undefined).
|
|
1654
|
+
*/
|
|
1655
|
+
async processNestedUpdate(client, parentType, parentId, parentRelation, childId, _query, requestBody) {
|
|
1656
|
+
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
1657
|
+
if (!resolved) return this.makeError("invalidPath");
|
|
1658
|
+
const parentInfo = this.getModelInfo(parentType);
|
|
1659
|
+
const childType = resolved.childType;
|
|
1660
|
+
const typeInfo = this.getModelInfo(childType);
|
|
1661
|
+
const { updateData, error } = this.buildNestedUpdatePayload(childType, typeInfo, resolved.reverseRelation, requestBody);
|
|
1662
|
+
if (error) return error;
|
|
1663
|
+
if (childId) {
|
|
1664
|
+
await client[parentType].update({
|
|
1665
|
+
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
1666
|
+
data: { [parentRelation]: { update: {
|
|
1667
|
+
where: this.makeIdFilter(typeInfo.idFields, childId),
|
|
1668
|
+
data: updateData
|
|
1669
|
+
} } }
|
|
1670
|
+
});
|
|
1671
|
+
const fetchArgs = { where: this.makeIdFilter(typeInfo.idFields, childId) };
|
|
1672
|
+
this.includeRelationshipIds(childType, fetchArgs, "include");
|
|
1673
|
+
const entity = await client[childType].findUnique(fetchArgs);
|
|
1674
|
+
if (!entity) return this.makeError("notFound");
|
|
1675
|
+
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation, childId));
|
|
1676
|
+
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
1677
|
+
return {
|
|
1678
|
+
status: 200,
|
|
1679
|
+
body: await this.serializeItems(childType, entity, { linkers: {
|
|
1680
|
+
document: nestedLinker,
|
|
1681
|
+
resource: nestedLinker
|
|
1682
|
+
} })
|
|
1683
|
+
};
|
|
1684
|
+
} else {
|
|
1685
|
+
await client[parentType].update({
|
|
1686
|
+
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
1687
|
+
data: { [parentRelation]: { update: updateData } }
|
|
1688
|
+
});
|
|
1689
|
+
const childIncludeArgs = {};
|
|
1690
|
+
this.includeRelationshipIds(childType, childIncludeArgs, "include");
|
|
1691
|
+
const fetchArgs = {
|
|
1692
|
+
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
1693
|
+
select: { [parentRelation]: childIncludeArgs.include ? { include: childIncludeArgs.include } : true }
|
|
1694
|
+
};
|
|
1695
|
+
const entity = (await client[parentType].findUnique(fetchArgs))?.[parentRelation];
|
|
1696
|
+
if (!entity) return this.makeError("notFound");
|
|
1697
|
+
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation));
|
|
1698
|
+
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
1699
|
+
return {
|
|
1700
|
+
status: 200,
|
|
1701
|
+
body: await this.serializeItems(childType, entity, { linkers: {
|
|
1702
|
+
document: nestedLinker,
|
|
1703
|
+
resource: nestedLinker
|
|
1704
|
+
} })
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
async processNestedDelete(client, parentType, parentId, parentRelation, childId) {
|
|
1709
|
+
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
1710
|
+
if (!resolved) return this.makeError("invalidPath");
|
|
1711
|
+
const parentInfo = this.getModelInfo(parentType);
|
|
1712
|
+
const typeInfo = this.getModelInfo(resolved.childType);
|
|
1713
|
+
await client[parentType].update({
|
|
1714
|
+
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
1715
|
+
data: { [parentRelation]: { delete: this.makeIdFilter(typeInfo.idFields, childId) } }
|
|
1716
|
+
});
|
|
1717
|
+
return {
|
|
1718
|
+
status: 200,
|
|
1719
|
+
body: { meta: {} }
|
|
1720
|
+
};
|
|
1721
|
+
}
|
|
1722
|
+
buildPartialSelect(type, query) {
|
|
1723
|
+
const selectFieldsQuery = query?.[`fields[${type}]`];
|
|
1724
|
+
if (!selectFieldsQuery) return {
|
|
1725
|
+
select: void 0,
|
|
1726
|
+
error: void 0
|
|
1727
|
+
};
|
|
1728
|
+
if (Array.isArray(selectFieldsQuery)) return {
|
|
1729
|
+
select: void 0,
|
|
1730
|
+
error: this.makeError("duplicatedFieldsParameter", `duplicated fields query for type ${type}`)
|
|
1731
|
+
};
|
|
1732
|
+
const typeInfo = this.getModelInfo(type);
|
|
1733
|
+
if (!typeInfo) return {
|
|
1734
|
+
select: void 0,
|
|
1735
|
+
error: this.makeUnsupportedModelError(type)
|
|
1736
|
+
};
|
|
1737
|
+
const fields = selectFieldsQuery.split(",").filter((i) => i).reduce((acc, curr) => ({
|
|
1738
|
+
...acc,
|
|
1739
|
+
[curr]: true
|
|
1740
|
+
}), {});
|
|
1741
|
+
return { select: {
|
|
1742
|
+
...this.makeIdSelect(typeInfo.idFields),
|
|
1743
|
+
...fields
|
|
1744
|
+
} };
|
|
1745
|
+
}
|
|
1746
|
+
addTotalCountToMeta(meta, total) {
|
|
1747
|
+
return meta ? Object.assign(meta, { total }) : Object.assign({}, { total });
|
|
1748
|
+
}
|
|
1749
|
+
makePaginator(baseUrl, offset, limit, total) {
|
|
1750
|
+
if (limit === Infinity) return;
|
|
1751
|
+
const totalPages = Math.ceil(total / limit);
|
|
1752
|
+
return new tsjapi.Paginator(() => ({
|
|
1753
|
+
first: this.replaceURLSearchParams(baseUrl, { "page[limit]": limit }),
|
|
1754
|
+
last: this.replaceURLSearchParams(baseUrl, { "page[offset]": (totalPages - 1) * limit }),
|
|
1755
|
+
prev: offset - limit >= 0 && offset - limit <= total - 1 ? this.replaceURLSearchParams(baseUrl, {
|
|
1756
|
+
"page[offset]": offset - limit,
|
|
1757
|
+
"page[limit]": limit
|
|
1758
|
+
}) : null,
|
|
1759
|
+
next: offset + limit <= total - 1 ? this.replaceURLSearchParams(baseUrl, {
|
|
1760
|
+
"page[offset]": offset + limit,
|
|
1761
|
+
"page[limit]": limit
|
|
1762
|
+
}) : null
|
|
1763
|
+
}));
|
|
1764
|
+
}
|
|
1765
|
+
processRequestBody(requestBody) {
|
|
1766
|
+
let body = requestBody;
|
|
1767
|
+
if (body.meta?.serialization) body = SuperJSON.deserialize({
|
|
1768
|
+
json: body,
|
|
1769
|
+
meta: body.meta.serialization
|
|
1770
|
+
});
|
|
1771
|
+
const parseResult = this.createUpdatePayloadSchema.safeParse(body);
|
|
1772
|
+
if (!parseResult.success) return {
|
|
1773
|
+
attributes: void 0,
|
|
1774
|
+
relationships: void 0,
|
|
1775
|
+
error: this.makeError("invalidPayload", getZodErrorMessage(parseResult.error))
|
|
1776
|
+
};
|
|
1777
|
+
return {
|
|
1778
|
+
attributes: parseResult.data.data.attributes,
|
|
1779
|
+
relationships: parseResult.data.data.relationships,
|
|
1780
|
+
error: void 0
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
async processCreate(client, type, _query, requestBody) {
|
|
1784
|
+
const typeInfo = this.getModelInfo(type);
|
|
1785
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1786
|
+
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
1787
|
+
if (error) return error;
|
|
1788
|
+
const createPayload = { data: { ...attributes } };
|
|
1789
|
+
if (relationships) for (const [key, data] of Object.entries(relationships)) {
|
|
1790
|
+
if (!data?.data) return this.makeError("invalidRelationData");
|
|
1791
|
+
const relationInfo = typeInfo.relationships[key];
|
|
1792
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(type, key, 400);
|
|
1793
|
+
if (relationInfo.isCollection) createPayload.data[key] = { connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id)) };
|
|
1794
|
+
else {
|
|
1795
|
+
if (typeof data.data !== "object") return this.makeError("invalidRelationData");
|
|
1796
|
+
createPayload.data[key] = { connect: this.makeIdConnect(relationInfo.idFields, data.data.id) };
|
|
1797
|
+
}
|
|
1798
|
+
createPayload.include = {
|
|
1799
|
+
...createPayload.include,
|
|
1800
|
+
[key]: { select: { [this.makeDefaultIdKey(relationInfo.idFields)]: true } }
|
|
1801
|
+
};
|
|
1802
|
+
}
|
|
1803
|
+
this.includeRelationshipIds(type, createPayload, "include");
|
|
1804
|
+
const entity = await client[type].create(createPayload);
|
|
1805
|
+
return {
|
|
1806
|
+
status: 201,
|
|
1807
|
+
body: await this.serializeItems(type, entity)
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
async processUpsert(client, type, _query, requestBody) {
|
|
1811
|
+
const typeInfo = this.getModelInfo(type);
|
|
1812
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1813
|
+
const modelName = typeInfo.name;
|
|
1814
|
+
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
1815
|
+
if (error) return error;
|
|
1816
|
+
const parseResult = this.upsertMetaSchema.safeParse(requestBody);
|
|
1817
|
+
if (parseResult.error) return this.makeError("invalidPayload", getZodErrorMessage(parseResult.error));
|
|
1818
|
+
const matchFields = parseResult.data.meta.matchFields;
|
|
1819
|
+
if (!this.getUniqueFieldSets(modelName).some((set) => set.every((field) => matchFields.includes(field)))) return this.makeError("invalidPayload", "Match fields must be unique fields", 400);
|
|
1820
|
+
const upsertPayload = {
|
|
1821
|
+
where: this.makeUpsertWhere(matchFields, attributes, typeInfo),
|
|
1822
|
+
create: { ...attributes },
|
|
1823
|
+
update: { ...Object.fromEntries(Object.entries(attributes ?? {}).filter((e) => !matchFields.includes(e[0]))) }
|
|
1824
|
+
};
|
|
1825
|
+
if (relationships) for (const [key, data] of Object.entries(relationships)) {
|
|
1826
|
+
if (!data?.data) return this.makeError("invalidRelationData");
|
|
1827
|
+
const relationInfo = typeInfo.relationships[key];
|
|
1828
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(modelName, key, 400);
|
|
1829
|
+
if (relationInfo.isCollection) {
|
|
1830
|
+
upsertPayload.create[key] = { connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id)) };
|
|
1831
|
+
upsertPayload.update[key] = { set: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id)) };
|
|
1832
|
+
} else {
|
|
1833
|
+
if (typeof data.data !== "object") return this.makeError("invalidRelationData");
|
|
1834
|
+
upsertPayload.create[key] = { connect: this.makeIdConnect(relationInfo.idFields, data.data.id) };
|
|
1835
|
+
upsertPayload.update[key] = { connect: this.makeIdConnect(relationInfo.idFields, data.data.id) };
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
this.includeRelationshipIds(modelName, upsertPayload, "include");
|
|
1839
|
+
const entity = await client[modelName].upsert(upsertPayload);
|
|
1840
|
+
return {
|
|
1841
|
+
status: 201,
|
|
1842
|
+
body: await this.serializeItems(modelName, entity)
|
|
1843
|
+
};
|
|
1844
|
+
}
|
|
1845
|
+
getUniqueFieldSets(type) {
|
|
1846
|
+
const modelDef = this.requireModel(type);
|
|
1847
|
+
return Object.entries(modelDef.uniqueFields).map(([k, v]) => typeof v.type === "string" ? [k] : Object.keys(v));
|
|
1848
|
+
}
|
|
1849
|
+
async processRelationshipCRUD(client, mode, type, resourceId, relationship, _query, requestBody) {
|
|
1850
|
+
const typeInfo = this.getModelInfo(type);
|
|
1851
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1852
|
+
const relationInfo = typeInfo.relationships[relationship];
|
|
1853
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
1854
|
+
if (!relationInfo.isCollection && mode !== "update") return this.makeError("invalidVerb");
|
|
1855
|
+
const updateArgs = {
|
|
1856
|
+
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
1857
|
+
select: {
|
|
1858
|
+
...typeInfo.idFields.reduce((acc, field) => ({
|
|
1859
|
+
...acc,
|
|
1860
|
+
[field.name]: true
|
|
1861
|
+
}), {}),
|
|
1862
|
+
[relationship]: { select: this.makeIdSelect(relationInfo.idFields) }
|
|
1863
|
+
}
|
|
1864
|
+
};
|
|
1865
|
+
if (!relationInfo.isCollection) {
|
|
1866
|
+
const parsed = this.updateSingleRelationSchema.safeParse(requestBody);
|
|
1867
|
+
if (!parsed.success) return this.makeError("invalidPayload", getZodErrorMessage(parsed.error));
|
|
1868
|
+
if (parsed.data.data === null) {
|
|
1869
|
+
if (!relationInfo.isOptional) return this.makeError("invalidPayload");
|
|
1870
|
+
updateArgs.data = { [relationship]: { disconnect: true } };
|
|
1871
|
+
} else updateArgs.data = { [relationship]: { connect: this.makeIdConnect(relationInfo.idFields, parsed.data.data.id) } };
|
|
1872
|
+
} else {
|
|
1873
|
+
const parsed = this.updateCollectionRelationSchema.safeParse(requestBody);
|
|
1874
|
+
if (!parsed.success) return this.makeError("invalidPayload", getZodErrorMessage(parsed.error));
|
|
1875
|
+
const relationVerb = mode === "create" ? "connect" : mode === "delete" ? "disconnect" : "set";
|
|
1876
|
+
updateArgs.data = { [relationship]: { [relationVerb]: enumerate(parsed.data.data).map((item) => this.makeIdFilter(relationInfo.idFields, item.id)) } };
|
|
1877
|
+
}
|
|
1878
|
+
const entity = await client[type].update(updateArgs);
|
|
1879
|
+
const mappedType = this.mapModelName(type);
|
|
1880
|
+
return {
|
|
1881
|
+
status: 200,
|
|
1882
|
+
body: await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
1883
|
+
linkers: { document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`)) },
|
|
1884
|
+
onlyIdentifier: true
|
|
1885
|
+
})
|
|
1886
|
+
};
|
|
1887
|
+
}
|
|
1888
|
+
async processUpdate(client, type, resourceId, _query, requestBody) {
|
|
1889
|
+
const typeInfo = this.getModelInfo(type);
|
|
1890
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1891
|
+
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
1892
|
+
if (error) return error;
|
|
1893
|
+
const updatePayload = {
|
|
1894
|
+
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
1895
|
+
data: { ...attributes }
|
|
1896
|
+
};
|
|
1897
|
+
if (relationships) for (const [key, data] of Object.entries(relationships)) {
|
|
1898
|
+
if (!data?.data) return this.makeError("invalidRelationData");
|
|
1899
|
+
const relationInfo = typeInfo.relationships[key];
|
|
1900
|
+
if (!relationInfo) return this.makeUnsupportedRelationshipError(type, key, 400);
|
|
1901
|
+
if (relationInfo.isCollection) updatePayload.data[key] = { set: enumerate(data.data).map((item) => ({ [this.makeDefaultIdKey(relationInfo.idFields)]: item.id })) };
|
|
1902
|
+
else {
|
|
1903
|
+
if (typeof data.data !== "object") return this.makeError("invalidRelationData");
|
|
1904
|
+
updatePayload.data[key] = { connect: { [this.makeDefaultIdKey(relationInfo.idFields)]: data.data.id } };
|
|
1905
|
+
}
|
|
1906
|
+
updatePayload.include = {
|
|
1907
|
+
...updatePayload.include,
|
|
1908
|
+
[key]: { select: { [this.makeDefaultIdKey(relationInfo.idFields)]: true } }
|
|
1909
|
+
};
|
|
1910
|
+
}
|
|
1911
|
+
this.includeRelationshipIds(type, updatePayload, "include");
|
|
1912
|
+
const entity = await client[type].update(updatePayload);
|
|
1913
|
+
return {
|
|
1914
|
+
status: 200,
|
|
1915
|
+
body: await this.serializeItems(type, entity)
|
|
1916
|
+
};
|
|
1917
|
+
}
|
|
1918
|
+
async processDelete(client, type, resourceId) {
|
|
1919
|
+
const typeInfo = this.getModelInfo(type);
|
|
1920
|
+
if (!typeInfo) return this.makeUnsupportedModelError(type);
|
|
1921
|
+
await client[type].delete({ where: this.makeIdFilter(typeInfo.idFields, resourceId) });
|
|
1922
|
+
return {
|
|
1923
|
+
status: 200,
|
|
1924
|
+
body: { meta: {} }
|
|
1925
|
+
};
|
|
1926
|
+
}
|
|
1927
|
+
requireModel(model) {
|
|
1928
|
+
const modelDef = this.schema.models[model];
|
|
1929
|
+
if (!modelDef) throw new Error(`Model ${model} is not defined in the schema`);
|
|
1930
|
+
return modelDef;
|
|
1931
|
+
}
|
|
1932
|
+
getIdFields(model) {
|
|
1933
|
+
const modelDef = this.requireModel(model);
|
|
1934
|
+
const modelLower = lowerCaseFirst(model);
|
|
1935
|
+
if (!(modelLower in this.externalIdMapping)) return Object.values(modelDef.fields).filter((f) => modelDef.idFields.includes(f.name));
|
|
1936
|
+
const externalIdName = this.externalIdMapping[modelLower];
|
|
1937
|
+
for (const [name, info] of Object.entries(modelDef.uniqueFields)) if (name === externalIdName) if (typeof info.type === "string") return [this.requireField(model, name)];
|
|
1938
|
+
else return Object.keys(info).map((f) => this.requireField(model, f));
|
|
1939
|
+
throw new Error(`Model ${model} does not have unique key ${externalIdName}`);
|
|
1940
|
+
}
|
|
1941
|
+
requireField(model, field) {
|
|
1942
|
+
const fieldDef = this.requireModel(model).fields[field];
|
|
1943
|
+
if (!fieldDef) throw new Error(`Field ${field} is not defined in model ${model}`);
|
|
1944
|
+
return fieldDef;
|
|
1945
|
+
}
|
|
1946
|
+
buildTypeMap() {
|
|
1947
|
+
this.typeMap = {};
|
|
1948
|
+
for (const [model, { fields }] of Object.entries(this.schema.models)) {
|
|
1949
|
+
const idFields = this.getIdFields(model);
|
|
1950
|
+
if (idFields.length === 0) {
|
|
1951
|
+
log(this.options.log, "warn", `Not including model ${model} in the API because it has no ID field`);
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
const modelInfo = this.typeMap[lowerCaseFirst(model)] = {
|
|
1955
|
+
name: model,
|
|
1956
|
+
idFields,
|
|
1957
|
+
relationships: {},
|
|
1958
|
+
fields
|
|
1959
|
+
};
|
|
1960
|
+
for (const [field, fieldInfo] of Object.entries(fields)) {
|
|
1961
|
+
if (!fieldInfo.relation) continue;
|
|
1962
|
+
const fieldTypeIdFields = this.getIdFields(fieldInfo.type);
|
|
1963
|
+
if (fieldTypeIdFields.length === 0) {
|
|
1964
|
+
log(this.options.log, "warn", `Not including relation ${model}.${field} in the API because it has no ID field`);
|
|
1965
|
+
continue;
|
|
1966
|
+
}
|
|
1967
|
+
modelInfo.relationships[field] = {
|
|
1968
|
+
type: fieldInfo.type,
|
|
1969
|
+
idFields: fieldTypeIdFields,
|
|
1970
|
+
isCollection: !!fieldInfo.array,
|
|
1971
|
+
isOptional: !!fieldInfo.optional
|
|
1972
|
+
};
|
|
1973
|
+
}
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
getModelInfo(model) {
|
|
1977
|
+
return this.typeMap[lowerCaseFirst(model)];
|
|
1978
|
+
}
|
|
1979
|
+
makeLinkUrl(path) {
|
|
1980
|
+
return `${this.options.endpoint}${path}`;
|
|
1981
|
+
}
|
|
1982
|
+
buildSerializers() {
|
|
1983
|
+
const linkers = {};
|
|
1984
|
+
for (const model of Object.keys(this.schema.models)) {
|
|
1985
|
+
const ids = this.getIdFields(model);
|
|
1986
|
+
const modelLower = lowerCaseFirst(model);
|
|
1987
|
+
const mappedModel = this.mapModelName(modelLower);
|
|
1988
|
+
if (ids.length < 1) continue;
|
|
1989
|
+
const linker = new tsjapi.Linker((items) => Array.isArray(items) ? this.makeLinkUrl(`/${mappedModel}`) : this.makeLinkUrl(`/${mappedModel}/${this.getId(model, items)}`));
|
|
1990
|
+
linkers[modelLower] = linker;
|
|
1991
|
+
let projection = {};
|
|
1992
|
+
const modelDef = this.requireModel(model);
|
|
1993
|
+
for (const [field, fieldDef] of Object.entries(modelDef.fields)) if (fieldDef.relation) projection[field] = 0;
|
|
1994
|
+
if (Object.keys(projection).length === 0) projection = null;
|
|
1995
|
+
const serializer = new tsjapi.Serializer(model, {
|
|
1996
|
+
version: "1.1",
|
|
1997
|
+
idKey: this.makeIdKey(ids),
|
|
1998
|
+
linkers: {
|
|
1999
|
+
resource: linker,
|
|
2000
|
+
document: linker
|
|
2001
|
+
},
|
|
2002
|
+
projection
|
|
2003
|
+
});
|
|
2004
|
+
this.serializers.set(modelLower, serializer);
|
|
2005
|
+
}
|
|
2006
|
+
for (const model of Object.keys(this.schema.models)) {
|
|
2007
|
+
const modelLower = lowerCaseFirst(model);
|
|
2008
|
+
const serializer = this.serializers.get(modelLower);
|
|
2009
|
+
if (!serializer) continue;
|
|
2010
|
+
const relators = {};
|
|
2011
|
+
const modelDef = this.requireModel(model);
|
|
2012
|
+
for (const [field, fieldDef] of Object.entries(modelDef.fields)) {
|
|
2013
|
+
if (!fieldDef.relation) continue;
|
|
2014
|
+
const fieldSerializer = this.serializers.get(lowerCaseFirst(fieldDef.type));
|
|
2015
|
+
if (!fieldSerializer) continue;
|
|
2016
|
+
if (this.getIdFields(fieldDef.type).length > 0) {
|
|
2017
|
+
const mappedModel = this.mapModelName(modelLower);
|
|
2018
|
+
relators[field] = new tsjapi.Relator(async (data) => {
|
|
2019
|
+
return data[field];
|
|
2020
|
+
}, fieldSerializer, {
|
|
2021
|
+
relatedName: field,
|
|
2022
|
+
linkers: {
|
|
2023
|
+
related: new tsjapi.Linker((primary) => this.makeLinkUrl(`/${mappedModel}/${this.getId(model, primary)}/${field}`)),
|
|
2024
|
+
relationship: new tsjapi.Linker((primary) => this.makeLinkUrl(`/${mappedModel}/${this.getId(model, primary)}/relationships/${field}`))
|
|
2025
|
+
}
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
serializer.setRelators(relators);
|
|
2030
|
+
}
|
|
2031
|
+
}
|
|
2032
|
+
getId(model, data) {
|
|
2033
|
+
if (!data) return;
|
|
2034
|
+
const ids = this.getIdFields(model);
|
|
2035
|
+
if (ids.length === 0) return;
|
|
2036
|
+
else return data[this.makeIdKey(ids)];
|
|
2037
|
+
}
|
|
2038
|
+
async serializeItems(model, items, options) {
|
|
2039
|
+
model = lowerCaseFirst(model);
|
|
2040
|
+
const serializer = this.serializers.get(model);
|
|
2041
|
+
if (!serializer) throw new Error(`serializer not found for model ${model}`);
|
|
2042
|
+
const itemsWithId = clone(items);
|
|
2043
|
+
this.injectCompoundId(model, itemsWithId);
|
|
2044
|
+
const serialized = await serializer.serialize(itemsWithId, options);
|
|
2045
|
+
const plainResult = this.toPlainObject(serialized);
|
|
2046
|
+
const { json, meta } = SuperJSON.serialize(plainResult);
|
|
2047
|
+
const result = json;
|
|
2048
|
+
if (meta) result.meta = {
|
|
2049
|
+
...result.meta,
|
|
2050
|
+
serialization: meta
|
|
2051
|
+
};
|
|
2052
|
+
return result;
|
|
2053
|
+
}
|
|
2054
|
+
injectCompoundId(model, items) {
|
|
2055
|
+
const typeInfo = this.getModelInfo(model);
|
|
2056
|
+
if (!typeInfo) return;
|
|
2057
|
+
enumerate(items).forEach((item) => {
|
|
2058
|
+
if (!item) return;
|
|
2059
|
+
if (typeInfo.idFields.length > 1) item[this.makeIdKey(typeInfo.idFields)] = this.makeCompoundId(typeInfo.idFields, item);
|
|
2060
|
+
for (const [key, value] of Object.entries(item)) if (typeInfo.relationships[key]) this.injectCompoundId(typeInfo.relationships[key].type, value);
|
|
2061
|
+
});
|
|
2062
|
+
}
|
|
2063
|
+
toPlainObject(data) {
|
|
2064
|
+
if (data === void 0 || data === null) return data;
|
|
2065
|
+
if (Array.isArray(data)) return data.map((item) => this.toPlainObject(item));
|
|
2066
|
+
if (typeof data === "object") {
|
|
2067
|
+
if (typeof data.toJSON === "function") return data.toJSON();
|
|
2068
|
+
const result = {};
|
|
2069
|
+
for (const [field, value] of Object.entries(data)) if (value === void 0 || typeof value === "function") continue;
|
|
2070
|
+
else if (field === "attributes") result[field] = value;
|
|
2071
|
+
else result[field] = this.toPlainObject(value);
|
|
2072
|
+
return result;
|
|
2073
|
+
}
|
|
2074
|
+
return data;
|
|
2075
|
+
}
|
|
2076
|
+
replaceURLSearchParams(url, params) {
|
|
2077
|
+
const r = new URL(url);
|
|
2078
|
+
for (const [key, value] of Object.entries(params)) r.searchParams.set(key, value.toString());
|
|
2079
|
+
return r.toString();
|
|
2080
|
+
}
|
|
2081
|
+
makeIdFilter(idFields, resourceId, nested = true) {
|
|
2082
|
+
const decodedId = decodeURIComponent(resourceId);
|
|
2083
|
+
if (idFields.length === 1) return { [idFields[0].name]: this.coerce(idFields[0], decodedId) };
|
|
2084
|
+
else if (nested) return { [idFields.map((idf) => idf.name).join(DEFAULT_ID_DIVIDER)]: idFields.reduce((acc, curr, idx) => ({
|
|
2085
|
+
...acc,
|
|
2086
|
+
[curr.name]: this.coerce(curr, decodedId.split(this.idDivider)[idx])
|
|
2087
|
+
}), {}) };
|
|
2088
|
+
else return idFields.reduce((acc, curr, idx) => ({
|
|
2089
|
+
...acc,
|
|
2090
|
+
[curr.name]: this.coerce(curr, decodedId.split(this.idDivider)[idx])
|
|
2091
|
+
}), {});
|
|
2092
|
+
}
|
|
2093
|
+
makeIdSelect(idFields) {
|
|
2094
|
+
if (idFields.length === 0) throw this.errors["noId"];
|
|
2095
|
+
return idFields.reduce((acc, curr) => ({
|
|
2096
|
+
...acc,
|
|
2097
|
+
[curr.name]: true
|
|
2098
|
+
}), {});
|
|
2099
|
+
}
|
|
2100
|
+
makeIdConnect(idFields, id) {
|
|
2101
|
+
if (idFields.length === 1) return { [idFields[0].name]: this.coerce(idFields[0], id) };
|
|
2102
|
+
else return { [this.makeDefaultIdKey(idFields)]: idFields.reduce((acc, curr, idx) => ({
|
|
2103
|
+
...acc,
|
|
2104
|
+
[curr.name]: this.coerce(curr, `${id}`.split(this.idDivider)[idx])
|
|
2105
|
+
}), {}) };
|
|
2106
|
+
}
|
|
2107
|
+
makeIdKey(idFields) {
|
|
2108
|
+
return idFields.map((idf) => idf.name).join(this.idDivider);
|
|
2109
|
+
}
|
|
2110
|
+
makeDefaultIdKey(idFields) {
|
|
2111
|
+
return idFields.map((idf) => idf.name).join(DEFAULT_ID_DIVIDER);
|
|
2112
|
+
}
|
|
2113
|
+
makeCompoundId(idFields, item) {
|
|
2114
|
+
return idFields.map((idf) => item[idf.name]).join(this.idDivider);
|
|
2115
|
+
}
|
|
2116
|
+
makeUpsertWhere(matchFields, attributes, typeInfo) {
|
|
2117
|
+
const where = matchFields.reduce((acc, field) => {
|
|
2118
|
+
acc[field] = attributes[field] ?? null;
|
|
2119
|
+
return acc;
|
|
2120
|
+
}, {});
|
|
2121
|
+
if (typeInfo.idFields.length > 1 && matchFields.some((mf) => typeInfo.idFields.map((idf) => idf.name).includes(mf))) return { [this.makeDefaultIdKey(typeInfo.idFields)]: where };
|
|
2122
|
+
return where;
|
|
2123
|
+
}
|
|
2124
|
+
includeRelationshipIds(model, args, mode) {
|
|
2125
|
+
const typeInfo = this.getModelInfo(model);
|
|
2126
|
+
if (!typeInfo) return;
|
|
2127
|
+
for (const [relation, relationInfo] of Object.entries(typeInfo.relationships)) args[mode] = {
|
|
2128
|
+
...args[mode],
|
|
2129
|
+
[relation]: { select: this.makeIdSelect(relationInfo.idFields) }
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
coerce(fieldDef, value) {
|
|
2133
|
+
if (typeof value === "string") {
|
|
2134
|
+
if (fieldDef.attributes?.some((attr) => attr.name === "@json")) try {
|
|
2135
|
+
return JSON.parse(value);
|
|
2136
|
+
} catch {
|
|
2137
|
+
throw new InvalidValueError(`invalid JSON value: ${value}`);
|
|
2138
|
+
}
|
|
2139
|
+
const type = fieldDef.type;
|
|
2140
|
+
if (type === "Int") {
|
|
2141
|
+
const parsed = parseInt(value);
|
|
2142
|
+
if (isNaN(parsed)) throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
2143
|
+
return parsed;
|
|
2144
|
+
} else if (type === "BigInt") try {
|
|
2145
|
+
return BigInt(value);
|
|
2146
|
+
} catch {
|
|
2147
|
+
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
2148
|
+
}
|
|
2149
|
+
else if (type === "Float") {
|
|
2150
|
+
const parsed = parseFloat(value);
|
|
2151
|
+
if (isNaN(parsed)) throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
2152
|
+
return parsed;
|
|
2153
|
+
} else if (type === "Decimal") try {
|
|
2154
|
+
return new Decimal(value);
|
|
2155
|
+
} catch {
|
|
2156
|
+
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
2157
|
+
}
|
|
2158
|
+
else if (type === "Boolean") if (value === "true") return true;
|
|
2159
|
+
else if (value === "false") return false;
|
|
2160
|
+
else throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
2161
|
+
}
|
|
2162
|
+
return value;
|
|
2163
|
+
}
|
|
2164
|
+
makeNormalizedUrl(path, query) {
|
|
2165
|
+
const url = new URL(this.makeLinkUrl(path));
|
|
2166
|
+
for (const [key, value] of Object.entries(query ?? {})) if (key.startsWith("filter[") || key.startsWith("sort[") || key === "include" || key.startsWith("include[") || key.startsWith("fields[")) for (const v of enumerate(value)) url.searchParams.append(key, v);
|
|
2167
|
+
return url.toString();
|
|
2168
|
+
}
|
|
2169
|
+
getPagination(query) {
|
|
2170
|
+
if (!query) return {
|
|
2171
|
+
offset: 0,
|
|
2172
|
+
limit: this.options.pageSize ?? DEFAULT_PAGE_SIZE
|
|
2173
|
+
};
|
|
2174
|
+
let offset = 0;
|
|
2175
|
+
if (query["page[offset]"]) {
|
|
2176
|
+
const value = query["page[offset]"];
|
|
2177
|
+
const offsetText = Array.isArray(value) ? value[value.length - 1] : value;
|
|
2178
|
+
offset = parseInt(offsetText);
|
|
2179
|
+
if (isNaN(offset) || offset < 0) offset = 0;
|
|
2180
|
+
}
|
|
2181
|
+
let pageSizeOption = this.options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
2182
|
+
if (pageSizeOption <= 0) pageSizeOption = DEFAULT_PAGE_SIZE;
|
|
2183
|
+
let limit = pageSizeOption;
|
|
2184
|
+
if (query["page[limit]"]) {
|
|
2185
|
+
const value = query["page[limit]"];
|
|
2186
|
+
const limitText = Array.isArray(value) ? value[value.length - 1] : value;
|
|
2187
|
+
limit = parseInt(limitText);
|
|
2188
|
+
if (isNaN(limit) || limit <= 0) limit = pageSizeOption;
|
|
2189
|
+
limit = Math.min(pageSizeOption, limit);
|
|
2190
|
+
}
|
|
2191
|
+
return {
|
|
2192
|
+
offset,
|
|
2193
|
+
limit
|
|
2194
|
+
};
|
|
2195
|
+
}
|
|
2196
|
+
buildFilter(type, query) {
|
|
2197
|
+
if (!query) return {
|
|
2198
|
+
filter: void 0,
|
|
2199
|
+
error: void 0
|
|
2200
|
+
};
|
|
2201
|
+
const typeInfo = this.getModelInfo(type);
|
|
2202
|
+
if (!typeInfo) return {
|
|
2203
|
+
filter: void 0,
|
|
2204
|
+
error: this.makeUnsupportedModelError(type)
|
|
2205
|
+
};
|
|
2206
|
+
const items = [];
|
|
2207
|
+
for (const [key, value] of Object.entries(query)) {
|
|
2208
|
+
if (!value) continue;
|
|
2209
|
+
const match = key.match(this.filterParamPattern);
|
|
2210
|
+
if (!match || !match.groups || !match.groups["match"]) continue;
|
|
2211
|
+
const filterKeys = match.groups["match"].replaceAll(/[[\]]/g, " ").split(" ").filter((i) => i);
|
|
2212
|
+
if (!filterKeys.length) continue;
|
|
2213
|
+
const item = {};
|
|
2214
|
+
let curr = item;
|
|
2215
|
+
let currType = typeInfo;
|
|
2216
|
+
for (const filterValue of enumerate(value)) {
|
|
2217
|
+
for (let i = 0; i < filterKeys.length; i++) {
|
|
2218
|
+
let filterKey = filterKeys[i];
|
|
2219
|
+
let filterOp;
|
|
2220
|
+
const pos = filterKey.indexOf("$");
|
|
2221
|
+
if (pos > 0) {
|
|
2222
|
+
filterOp = filterKey.substring(pos + 1);
|
|
2223
|
+
filterKey = filterKey.substring(0, pos);
|
|
2224
|
+
}
|
|
2225
|
+
if (!!filterOp && !FilterOperations.includes(filterOp)) return {
|
|
2226
|
+
filter: void 0,
|
|
2227
|
+
error: this.makeError("invalidFilter", `invalid filter operation: ${filterOp}`)
|
|
2228
|
+
};
|
|
2229
|
+
const idFields = this.getIdFields(currType.name);
|
|
2230
|
+
const fieldDef = filterKey === "id" ? Object.values(currType.fields).find((f) => idFields.some((idf) => idf.name === f.name)) : currType.fields[filterKey];
|
|
2231
|
+
if (!fieldDef) return {
|
|
2232
|
+
filter: void 0,
|
|
2233
|
+
error: this.makeError("invalidFilter")
|
|
2234
|
+
};
|
|
2235
|
+
if (!fieldDef.relation) {
|
|
2236
|
+
if (i !== filterKeys.length - 1) return {
|
|
2237
|
+
filter: void 0,
|
|
2238
|
+
error: this.makeError("invalidFilter")
|
|
2239
|
+
};
|
|
2240
|
+
curr[fieldDef.name] = this.makeFilterValue(fieldDef, filterValue, filterOp);
|
|
2241
|
+
} else if (i === filterKeys.length - 1) curr[fieldDef.name] = this.makeFilterValue(fieldDef, filterValue, filterOp);
|
|
2242
|
+
else {
|
|
2243
|
+
if (fieldDef.array) {
|
|
2244
|
+
curr[fieldDef.name] = { some: {} };
|
|
2245
|
+
curr = curr[fieldDef.name].some;
|
|
2246
|
+
} else curr = curr[fieldDef.name] = {};
|
|
2247
|
+
currType = this.getModelInfo(fieldDef.type);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
items.push(item);
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
if (items.length === 0) return {
|
|
2254
|
+
filter: void 0,
|
|
2255
|
+
error: void 0
|
|
2256
|
+
};
|
|
2257
|
+
else return {
|
|
2258
|
+
filter: items.length === 1 ? items[0] : { AND: items },
|
|
2259
|
+
error: void 0
|
|
2260
|
+
};
|
|
2261
|
+
}
|
|
2262
|
+
buildSort(type, query) {
|
|
2263
|
+
if (!query?.["sort"]) return {
|
|
2264
|
+
sort: void 0,
|
|
2265
|
+
error: void 0
|
|
2266
|
+
};
|
|
2267
|
+
const typeInfo = this.getModelInfo(type);
|
|
2268
|
+
if (!typeInfo) return {
|
|
2269
|
+
sort: void 0,
|
|
2270
|
+
error: this.makeUnsupportedModelError(type)
|
|
2271
|
+
};
|
|
2272
|
+
const result = [];
|
|
2273
|
+
for (const sortSpec of enumerate(query["sort"])) {
|
|
2274
|
+
const sortFields = sortSpec.split(",").filter((i) => i);
|
|
2275
|
+
for (const sortField of sortFields) {
|
|
2276
|
+
const dir = sortField.startsWith("-") ? "desc" : "asc";
|
|
2277
|
+
const parts = (sortField.startsWith("-") ? sortField.substring(1) : sortField).split(".").filter((i) => i);
|
|
2278
|
+
const sortItem = {};
|
|
2279
|
+
let curr = sortItem;
|
|
2280
|
+
let currType = typeInfo;
|
|
2281
|
+
for (let i = 0; i < parts.length; i++) {
|
|
2282
|
+
const part = parts[i];
|
|
2283
|
+
const fieldInfo = currType.fields[part];
|
|
2284
|
+
if (!fieldInfo || fieldInfo.array) return {
|
|
2285
|
+
sort: void 0,
|
|
2286
|
+
error: this.makeError("invalidSort", "sorting by array field is not supported")
|
|
2287
|
+
};
|
|
2288
|
+
if (i === parts.length - 1) if (fieldInfo.relation) {
|
|
2289
|
+
const relationType = this.getModelInfo(fieldInfo.type);
|
|
2290
|
+
if (!relationType) return {
|
|
2291
|
+
sort: void 0,
|
|
2292
|
+
error: this.makeUnsupportedModelError(fieldInfo.type)
|
|
2293
|
+
};
|
|
2294
|
+
curr[fieldInfo.name] = relationType.idFields.reduce((acc, idField) => {
|
|
2295
|
+
acc[idField.name] = dir;
|
|
2296
|
+
return acc;
|
|
2297
|
+
}, {});
|
|
2298
|
+
} else curr[fieldInfo.name] = dir;
|
|
2299
|
+
else {
|
|
2300
|
+
if (!fieldInfo.relation) return {
|
|
2301
|
+
sort: void 0,
|
|
2302
|
+
error: this.makeError("invalidSort", "intermediate sort segments must be relationships")
|
|
2303
|
+
};
|
|
2304
|
+
curr = curr[fieldInfo.name] = {};
|
|
2305
|
+
currType = this.getModelInfo(fieldInfo.type);
|
|
2306
|
+
if (!currType) return {
|
|
2307
|
+
sort: void 0,
|
|
2308
|
+
error: this.makeUnsupportedModelError(fieldInfo.type)
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
result.push(sortItem);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
return {
|
|
2316
|
+
sort: result,
|
|
2317
|
+
error: void 0
|
|
2318
|
+
};
|
|
2319
|
+
}
|
|
2320
|
+
buildRelationSelect(type, include, query) {
|
|
2321
|
+
const typeInfo = this.getModelInfo(type);
|
|
2322
|
+
if (!typeInfo) return {
|
|
2323
|
+
select: void 0,
|
|
2324
|
+
error: this.makeUnsupportedModelError(type)
|
|
2325
|
+
};
|
|
2326
|
+
const result = {};
|
|
2327
|
+
const allIncludes = [];
|
|
2328
|
+
for (const includeItem of enumerate(include)) {
|
|
2329
|
+
const inclusions = includeItem.split(",").filter((i) => i);
|
|
2330
|
+
for (const inclusion of inclusions) {
|
|
2331
|
+
allIncludes.push(inclusion);
|
|
2332
|
+
const parts = inclusion.split(".");
|
|
2333
|
+
let currPayload = result;
|
|
2334
|
+
let currType = typeInfo;
|
|
2335
|
+
for (let i = 0; i < parts.length; i++) {
|
|
2336
|
+
const relation = parts[i];
|
|
2337
|
+
const relationInfo = currType.relationships[relation];
|
|
2338
|
+
if (!relationInfo) return {
|
|
2339
|
+
select: void 0,
|
|
2340
|
+
error: this.makeUnsupportedRelationshipError(type, relation, 400)
|
|
2341
|
+
};
|
|
2342
|
+
currType = this.getModelInfo(relationInfo.type);
|
|
2343
|
+
if (!currType) return {
|
|
2344
|
+
select: void 0,
|
|
2345
|
+
error: this.makeUnsupportedModelError(relationInfo.type)
|
|
2346
|
+
};
|
|
2347
|
+
const { select, error } = this.buildPartialSelect(lowerCaseFirst(relationInfo.type), query);
|
|
2348
|
+
if (error) return {
|
|
2349
|
+
select: void 0,
|
|
2350
|
+
error
|
|
2351
|
+
};
|
|
2352
|
+
if (i !== parts.length - 1) if (select) {
|
|
2353
|
+
currPayload[relation] = { select: { ...select } };
|
|
2354
|
+
currPayload = currPayload[relation].select;
|
|
2355
|
+
} else {
|
|
2356
|
+
currPayload[relation] = { include: { ...currPayload[relation]?.include } };
|
|
2357
|
+
currPayload = currPayload[relation].include;
|
|
2358
|
+
}
|
|
2359
|
+
else currPayload[relation] = select ? { select: { ...select } } : true;
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
return {
|
|
2364
|
+
select: result,
|
|
2365
|
+
error: void 0,
|
|
2366
|
+
allIncludes
|
|
2367
|
+
};
|
|
2368
|
+
}
|
|
2369
|
+
makeFilterValue(fieldDef, value, op) {
|
|
2370
|
+
if (fieldDef.relation) {
|
|
2371
|
+
const info = this.getModelInfo(fieldDef.type);
|
|
2372
|
+
if (fieldDef.array) {
|
|
2373
|
+
const values = value.split(",").filter((i) => i);
|
|
2374
|
+
return { some: values.length > 1 ? { OR: values.map((v) => this.makeIdFilter(info.idFields, v, false)) } : this.makeIdFilter(info.idFields, value, false) };
|
|
2375
|
+
} else {
|
|
2376
|
+
const values = value.split(",").filter((i) => i);
|
|
2377
|
+
if (values.length > 1) return { OR: values.map((v) => this.makeIdFilter(info.idFields, v, false)) };
|
|
2378
|
+
else return { is: this.makeIdFilter(info.idFields, value, false) };
|
|
2379
|
+
}
|
|
2380
|
+
} else {
|
|
2381
|
+
if (op === "between") {
|
|
2382
|
+
const parts = value.split(",").map((v) => this.coerce(fieldDef, v));
|
|
2383
|
+
if (parts.length !== 2) throw new InvalidValueError(`"between" expects exactly 2 comma-separated values`);
|
|
2384
|
+
return { between: [parts[0], parts[1]] };
|
|
2385
|
+
}
|
|
2386
|
+
const coerced = this.coerce(fieldDef, value);
|
|
2387
|
+
switch (op) {
|
|
2388
|
+
case "icontains": return {
|
|
2389
|
+
contains: coerced,
|
|
2390
|
+
mode: "insensitive"
|
|
2391
|
+
};
|
|
2392
|
+
case "hasSome":
|
|
2393
|
+
case "hasEvery": {
|
|
2394
|
+
const values = value.split(",").filter((i) => i).map((v) => this.coerce(fieldDef, v));
|
|
2395
|
+
return { [op]: values };
|
|
2396
|
+
}
|
|
2397
|
+
case "isEmpty":
|
|
2398
|
+
if (value !== "true" && value !== "false") throw new InvalidValueError(`Not a boolean: ${value}`);
|
|
2399
|
+
return { isEmpty: value === "true" ? true : false };
|
|
2400
|
+
default: if (op === void 0) {
|
|
2401
|
+
if (fieldDef.attributes?.some((attr) => attr.name === "@json")) return { equals: coerced };
|
|
2402
|
+
const values = value.split(",").filter((i) => i).map((v) => this.coerce(fieldDef, v));
|
|
2403
|
+
return values.length > 1 ? { in: values } : { equals: values[0] };
|
|
2404
|
+
} else return { [op]: coerced };
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
injectRelationQuery(type, injectTarget, injectKey, query) {
|
|
2409
|
+
const { filter, error: filterError } = this.buildFilter(type, query);
|
|
2410
|
+
if (filterError) return filterError;
|
|
2411
|
+
if (filter) injectTarget[injectKey] = {
|
|
2412
|
+
...injectTarget[injectKey],
|
|
2413
|
+
where: filter
|
|
2414
|
+
};
|
|
2415
|
+
const { sort, error: sortError } = this.buildSort(type, query);
|
|
2416
|
+
if (sortError) return sortError;
|
|
2417
|
+
if (sort) injectTarget[injectKey] = {
|
|
2418
|
+
...injectTarget[injectKey],
|
|
2419
|
+
orderBy: sort
|
|
2420
|
+
};
|
|
2421
|
+
const pagination = this.getPagination(query);
|
|
2422
|
+
const offset = pagination.offset;
|
|
2423
|
+
if (offset > 0) injectTarget[injectKey] = {
|
|
2424
|
+
...injectTarget[injectKey],
|
|
2425
|
+
skip: offset
|
|
2426
|
+
};
|
|
2427
|
+
const limit = pagination.limit;
|
|
2428
|
+
if (limit !== Infinity) {
|
|
2429
|
+
injectTarget[injectKey] = {
|
|
2430
|
+
...injectTarget[injectKey],
|
|
2431
|
+
take: limit
|
|
2432
|
+
};
|
|
2433
|
+
injectTarget._count = { select: { [injectKey]: true } };
|
|
2434
|
+
}
|
|
2435
|
+
}
|
|
2436
|
+
handleORMError(err) {
|
|
2437
|
+
return match(err.reason).with(ORMErrorReason.INVALID_INPUT, () => {
|
|
2438
|
+
return this.makeError("validationError", err.message, 422);
|
|
2439
|
+
}).with(ORMErrorReason.REJECTED_BY_POLICY, () => {
|
|
2440
|
+
return this.makeError("forbidden", err.message, 403, { reason: err.rejectedByPolicyReason });
|
|
2441
|
+
}).with(ORMErrorReason.NOT_FOUND, () => {
|
|
2442
|
+
return this.makeError("notFound", err.message, 404);
|
|
2443
|
+
}).with(ORMErrorReason.DB_QUERY_ERROR, () => {
|
|
2444
|
+
return this.makeError("queryError", err.message, 400, { dbErrorCode: err.dbErrorCode });
|
|
2445
|
+
}).otherwise(() => {
|
|
2446
|
+
return this.makeError("unknownError", err.message);
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
makeError(code, detail, status, otherFields = {}) {
|
|
2450
|
+
status = status ?? this.errors[code]?.status ?? 500;
|
|
2451
|
+
const error = {
|
|
2452
|
+
status,
|
|
2453
|
+
code: paramCase(code),
|
|
2454
|
+
title: this.errors[code]?.title
|
|
2455
|
+
};
|
|
2456
|
+
if (detail) error.detail = detail;
|
|
2457
|
+
Object.assign(error, otherFields);
|
|
2458
|
+
return {
|
|
2459
|
+
status,
|
|
2460
|
+
body: { errors: [error] }
|
|
2461
|
+
};
|
|
2462
|
+
}
|
|
2463
|
+
makeUnsupportedModelError(model) {
|
|
2464
|
+
return this.makeError("unsupportedModel", `Model ${model} doesn't exist`);
|
|
2465
|
+
}
|
|
2466
|
+
makeUnsupportedRelationshipError(model, relationship, status) {
|
|
2467
|
+
return this.makeError("unsupportedRelationship", `Relationship ${model}.${relationship} doesn't exist`, status);
|
|
2468
|
+
}
|
|
2469
|
+
async generateSpec(options) {
|
|
2470
|
+
return new RestApiSpecGenerator(this.options).generateSpec(options);
|
|
2471
|
+
}
|
|
2472
|
+
};
|
|
2473
|
+
//#endregion
|
|
2474
|
+
//#region src/api/rpc/index.ts
|
|
2475
|
+
const TRANSACTION_ROUTE_PREFIX = "$transaction";
|
|
2476
|
+
const VALID_OPS = new Set(CoreCrudOperations);
|
|
2477
|
+
registerCustomSerializers();
|
|
2478
|
+
/**
|
|
2479
|
+
* RPC style API request handler that mirrors the ZenStackClient API
|
|
2480
|
+
*/
|
|
2481
|
+
var RPCApiHandler = class {
|
|
2482
|
+
constructor(options) {
|
|
2483
|
+
this.options = options;
|
|
2484
|
+
this.validateOptions(options);
|
|
2485
|
+
}
|
|
2486
|
+
validateOptions(options) {
|
|
2487
|
+
const parseResult = z.strictObject({
|
|
2488
|
+
schema: z.object(),
|
|
2489
|
+
log: loggerSchema.optional(),
|
|
2490
|
+
queryOptions: queryOptionsSchema.optional()
|
|
2491
|
+
}).safeParse(options);
|
|
2492
|
+
if (!parseResult.success) throw new Error(`Invalid options: ${fromError(parseResult.error)}`);
|
|
2493
|
+
}
|
|
2494
|
+
get schema() {
|
|
2495
|
+
return this.options.schema;
|
|
2496
|
+
}
|
|
2497
|
+
get log() {
|
|
2498
|
+
return this.options.log;
|
|
2499
|
+
}
|
|
2500
|
+
async handleRequest({ client, method, path, query, requestBody }) {
|
|
2501
|
+
const parts = path.split("/").filter((p) => !!p);
|
|
2502
|
+
const op = parts.pop();
|
|
2503
|
+
let model = parts.pop();
|
|
2504
|
+
if (parts.length !== 0 || !op || !model) return this.makeBadInputErrorResponse("invalid request path");
|
|
2505
|
+
if (model === "$procs") return this.handleProcedureRequest({
|
|
2506
|
+
client,
|
|
2507
|
+
method: method.toUpperCase(),
|
|
2508
|
+
proc: op,
|
|
2509
|
+
query,
|
|
2510
|
+
requestBody
|
|
2511
|
+
});
|
|
2512
|
+
if (model === TRANSACTION_ROUTE_PREFIX) return this.handleTransaction({
|
|
2513
|
+
client,
|
|
2514
|
+
method: method.toUpperCase(),
|
|
2515
|
+
type: op,
|
|
2516
|
+
requestBody
|
|
2517
|
+
});
|
|
2518
|
+
model = lowerCaseFirst(model);
|
|
2519
|
+
method = method.toUpperCase();
|
|
2520
|
+
let args;
|
|
2521
|
+
let resCode = 200;
|
|
2522
|
+
switch (op) {
|
|
2523
|
+
case "create":
|
|
2524
|
+
case "createMany":
|
|
2525
|
+
case "createManyAndReturn":
|
|
2526
|
+
case "upsert":
|
|
2527
|
+
if (method !== "POST") return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
2528
|
+
if (!requestBody) return this.makeBadInputErrorResponse("missing request body");
|
|
2529
|
+
args = requestBody;
|
|
2530
|
+
resCode = 201;
|
|
2531
|
+
break;
|
|
2532
|
+
case "findFirst":
|
|
2533
|
+
case "findUnique":
|
|
2534
|
+
case "findMany":
|
|
2535
|
+
case "aggregate":
|
|
2536
|
+
case "groupBy":
|
|
2537
|
+
case "count":
|
|
2538
|
+
case "exists":
|
|
2539
|
+
if (method !== "GET") return this.makeBadInputErrorResponse("invalid request method, only GET is supported");
|
|
2540
|
+
try {
|
|
2541
|
+
args = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : {};
|
|
2542
|
+
} catch {
|
|
2543
|
+
return this.makeBadInputErrorResponse("invalid \"q\" query parameter");
|
|
2544
|
+
}
|
|
2545
|
+
break;
|
|
2546
|
+
case "update":
|
|
2547
|
+
case "updateMany":
|
|
2548
|
+
case "updateManyAndReturn":
|
|
2549
|
+
if (method !== "PUT" && method !== "PATCH") return this.makeBadInputErrorResponse("invalid request method, only PUT or PATCH are supported");
|
|
2550
|
+
if (!requestBody) return this.makeBadInputErrorResponse("missing request body");
|
|
2551
|
+
args = requestBody;
|
|
2552
|
+
break;
|
|
2553
|
+
case "delete":
|
|
2554
|
+
case "deleteMany":
|
|
2555
|
+
if (method !== "DELETE") return this.makeBadInputErrorResponse("invalid request method, only DELETE is supported");
|
|
2556
|
+
try {
|
|
2557
|
+
args = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : {};
|
|
2558
|
+
} catch (err) {
|
|
2559
|
+
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : "invalid \"q\" query parameter");
|
|
2560
|
+
}
|
|
2561
|
+
break;
|
|
2562
|
+
default: return this.makeBadInputErrorResponse("invalid operation: " + op);
|
|
2563
|
+
}
|
|
2564
|
+
const { result: processedArgs, error } = await this.processRequestPayload(args);
|
|
2565
|
+
if (error) return this.makeBadInputErrorResponse(error);
|
|
2566
|
+
try {
|
|
2567
|
+
if (!this.isValidModel(client, model)) return this.makeBadInputErrorResponse(`unknown model name: ${model}`);
|
|
2568
|
+
log(this.options.log, "debug", () => `handling "${model}.${op}" request with args: ${safeJSONStringify(processedArgs)}`);
|
|
2569
|
+
const clientResult = await client[model][op](processedArgs);
|
|
2570
|
+
let responseBody = { data: clientResult };
|
|
2571
|
+
if (clientResult) {
|
|
2572
|
+
const { json, meta } = SuperJSON.serialize(clientResult);
|
|
2573
|
+
responseBody = { data: json };
|
|
2574
|
+
if (meta) responseBody.meta = { serialization: meta };
|
|
2575
|
+
}
|
|
2576
|
+
const response = {
|
|
2577
|
+
status: resCode,
|
|
2578
|
+
body: responseBody
|
|
2579
|
+
};
|
|
2580
|
+
log(this.options.log, "debug", () => `sending response for "${model}.${op}" request: ${safeJSONStringify(response)}`);
|
|
2581
|
+
return response;
|
|
2582
|
+
} catch (err) {
|
|
2583
|
+
log(this.options.log, "error", `error occurred when handling "${model}.${op}" request`, err);
|
|
2584
|
+
if (err instanceof ORMError) return this.makeORMErrorResponse(err);
|
|
2585
|
+
else return this.makeGenericErrorResponse(err);
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
async handleTransaction({ client, method, type, requestBody }) {
|
|
2589
|
+
if (method !== "POST") return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
2590
|
+
if (type !== "sequential") return this.makeBadInputErrorResponse(`unsupported transaction type: ${type}`);
|
|
2591
|
+
if (!requestBody || !Array.isArray(requestBody) || requestBody.length === 0) return this.makeBadInputErrorResponse("request body must be a non-empty array of operations");
|
|
2592
|
+
const processedOps = [];
|
|
2593
|
+
for (let i = 0; i < requestBody.length; i++) {
|
|
2594
|
+
const item = requestBody[i];
|
|
2595
|
+
if (!item || typeof item !== "object") return this.makeBadInputErrorResponse(`operation at index ${i} must be an object`);
|
|
2596
|
+
const { model: itemModel, op: itemOp, args: itemArgs } = item;
|
|
2597
|
+
if (!itemModel || typeof itemModel !== "string") return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "model" field`);
|
|
2598
|
+
if (!itemOp || typeof itemOp !== "string") return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "op" field`);
|
|
2599
|
+
if (!VALID_OPS.has(itemOp)) return this.makeBadInputErrorResponse(`operation at index ${i} has invalid op: ${itemOp}`);
|
|
2600
|
+
if (!this.isValidModel(client, lowerCaseFirst(itemModel))) return this.makeBadInputErrorResponse(`operation at index ${i} has unknown model: ${itemModel}`);
|
|
2601
|
+
if (itemArgs !== void 0 && itemArgs !== null && (typeof itemArgs !== "object" || Array.isArray(itemArgs))) return this.makeBadInputErrorResponse(`operation at index ${i} has invalid "args" field`);
|
|
2602
|
+
const { result: processedArgs, error: argsError } = await this.processRequestPayload(itemArgs ?? {});
|
|
2603
|
+
if (argsError) return this.makeBadInputErrorResponse(`operation at index ${i}: ${argsError}`);
|
|
2604
|
+
processedOps.push({
|
|
2605
|
+
model: lowerCaseFirst(itemModel),
|
|
2606
|
+
op: itemOp,
|
|
2607
|
+
args: processedArgs
|
|
2608
|
+
});
|
|
2609
|
+
}
|
|
2610
|
+
try {
|
|
2611
|
+
const promises = processedOps.map(({ model, op, args }) => {
|
|
2612
|
+
return client[model][op](args);
|
|
2613
|
+
});
|
|
2614
|
+
log(this.options.log, "debug", () => `handling "$transaction" request with ${promises.length} operations`);
|
|
2615
|
+
const clientResult = await client.$transaction(promises);
|
|
2616
|
+
const { json, meta } = SuperJSON.serialize(clientResult);
|
|
2617
|
+
const responseBody = { data: json };
|
|
2618
|
+
if (meta) responseBody.meta = { serialization: meta };
|
|
2619
|
+
const response = {
|
|
2620
|
+
status: 200,
|
|
2621
|
+
body: responseBody
|
|
2622
|
+
};
|
|
2623
|
+
log(this.options.log, "debug", () => `sending response for "$transaction" request: ${safeJSONStringify(response)}`);
|
|
2624
|
+
return response;
|
|
2625
|
+
} catch (err) {
|
|
2626
|
+
log(this.options.log, "error", `error occurred when handling "$transaction" request`, err);
|
|
2627
|
+
if (err instanceof ORMError) return this.makeORMErrorResponse(err);
|
|
2628
|
+
return this.makeGenericErrorResponse(err);
|
|
2629
|
+
}
|
|
2630
|
+
}
|
|
2631
|
+
async handleProcedureRequest({ client, method, proc, query, requestBody }) {
|
|
2632
|
+
if (!proc) return this.makeBadInputErrorResponse("missing procedure name");
|
|
2633
|
+
const procDef = getProcedureDef(this.options.schema, proc);
|
|
2634
|
+
if (!procDef) return this.makeBadInputErrorResponse(`unknown procedure: ${proc}`);
|
|
2635
|
+
if (!!procDef.mutation) {
|
|
2636
|
+
if (method !== "POST") return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
2637
|
+
} else if (method !== "GET") return this.makeBadInputErrorResponse("invalid request method, only GET is supported");
|
|
2638
|
+
let argsPayload = method === "POST" ? requestBody : void 0;
|
|
2639
|
+
if (method === "GET") try {
|
|
2640
|
+
argsPayload = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : void 0;
|
|
2641
|
+
} catch (err) {
|
|
2642
|
+
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : "invalid \"q\" query parameter");
|
|
2643
|
+
}
|
|
2644
|
+
const { result: processedArgsPayload, error } = await processSuperJsonRequestPayload(argsPayload);
|
|
2645
|
+
if (error) return this.makeBadInputErrorResponse(error);
|
|
2646
|
+
let procInput;
|
|
2647
|
+
try {
|
|
2648
|
+
procInput = mapProcedureArgs(procDef, processedArgsPayload);
|
|
2649
|
+
} catch (err) {
|
|
2650
|
+
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : "invalid procedure arguments");
|
|
2651
|
+
}
|
|
2652
|
+
try {
|
|
2653
|
+
log(this.options.log, "debug", () => `handling "$procs.${proc}" request`);
|
|
2654
|
+
const clientResult = await client.$procs?.[proc](procInput);
|
|
2655
|
+
const { json, meta } = SuperJSON.serialize(clientResult);
|
|
2656
|
+
const responseBody = { data: json };
|
|
2657
|
+
if (meta) responseBody.meta = { serialization: meta };
|
|
2658
|
+
const response = {
|
|
2659
|
+
status: 200,
|
|
2660
|
+
body: responseBody
|
|
2661
|
+
};
|
|
2662
|
+
log(this.options.log, "debug", () => `sending response for "$procs.${proc}" request: ${safeJSONStringify(response)}`);
|
|
2663
|
+
return response;
|
|
2664
|
+
} catch (err) {
|
|
2665
|
+
log(this.options.log, "error", `error occurred when handling "$procs.${proc}" request`, err);
|
|
2666
|
+
if (err instanceof ORMError) return this.makeORMErrorResponse(err);
|
|
2667
|
+
return this.makeGenericErrorResponse(err);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
isValidModel(client, model) {
|
|
2671
|
+
return Object.keys(client.$schema.models).some((m) => lowerCaseFirst(m) === lowerCaseFirst(model));
|
|
2672
|
+
}
|
|
2673
|
+
makeBadInputErrorResponse(message) {
|
|
2674
|
+
const resp = {
|
|
2675
|
+
status: 400,
|
|
2676
|
+
body: { error: { message } }
|
|
2677
|
+
};
|
|
2678
|
+
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}`);
|
|
2679
|
+
return resp;
|
|
2680
|
+
}
|
|
2681
|
+
makeGenericErrorResponse(err) {
|
|
2682
|
+
const resp = {
|
|
2683
|
+
status: 500,
|
|
2684
|
+
body: { error: { message: err instanceof Error ? err.message : "unknown error" } }
|
|
2685
|
+
};
|
|
2686
|
+
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
2687
|
+
return resp;
|
|
2688
|
+
}
|
|
2689
|
+
makeORMErrorResponse(err) {
|
|
2690
|
+
let status = 400;
|
|
2691
|
+
const error = {
|
|
2692
|
+
message: err.message,
|
|
2693
|
+
reason: err.reason
|
|
2694
|
+
};
|
|
2695
|
+
match(err.reason).with(ORMErrorReason.NOT_FOUND, () => {
|
|
2696
|
+
status = 404;
|
|
2697
|
+
error.model = err.model;
|
|
2698
|
+
}).with(ORMErrorReason.INVALID_INPUT, () => {
|
|
2699
|
+
status = 422;
|
|
2700
|
+
error.rejectedByValidation = true;
|
|
2701
|
+
error.model = err.model;
|
|
2702
|
+
}).with(ORMErrorReason.REJECTED_BY_POLICY, () => {
|
|
2703
|
+
status = 403;
|
|
2704
|
+
error.rejectedByPolicy = true;
|
|
2705
|
+
error.model = err.model;
|
|
2706
|
+
error.rejectReason = err.rejectedByPolicyReason;
|
|
2707
|
+
}).with(ORMErrorReason.DB_QUERY_ERROR, () => {
|
|
2708
|
+
status = 400;
|
|
2709
|
+
error.dbErrorCode = err.dbErrorCode;
|
|
2710
|
+
}).otherwise(() => {});
|
|
2711
|
+
const resp = {
|
|
2712
|
+
status,
|
|
2713
|
+
body: { error }
|
|
2714
|
+
};
|
|
2715
|
+
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}`);
|
|
2716
|
+
return resp;
|
|
2717
|
+
}
|
|
2718
|
+
async generateSpec(options) {
|
|
2719
|
+
const { RPCApiSpecGenerator } = await import("./openapi-BPFL4Hn6.mjs");
|
|
2720
|
+
return new RPCApiSpecGenerator(this.options).generateSpec(options);
|
|
2721
|
+
}
|
|
2722
|
+
async processRequestPayload(args) {
|
|
2723
|
+
const { meta, ...rest } = args ?? {};
|
|
2724
|
+
if (meta?.serialization) try {
|
|
2725
|
+
args = SuperJSON.deserialize({
|
|
2726
|
+
json: rest,
|
|
2727
|
+
meta: meta.serialization
|
|
2728
|
+
});
|
|
2729
|
+
} catch (err) {
|
|
2730
|
+
return {
|
|
2731
|
+
result: void 0,
|
|
2732
|
+
error: `failed to deserialize request payload: ${err.message}`
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
else args = rest;
|
|
2736
|
+
return {
|
|
2737
|
+
result: args,
|
|
2738
|
+
error: void 0
|
|
2739
|
+
};
|
|
2740
|
+
}
|
|
2741
|
+
};
|
|
2742
|
+
//#endregion
|
|
2743
|
+
export { RPCApiHandler, RestApiHandler };
|
|
2744
|
+
|
|
2745
|
+
//# sourceMappingURL=api.mjs.map
|