@zenstackhq/server 3.5.6 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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.js
DELETED
|
@@ -1,4437 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
-
|
|
4
|
-
// src/api/rest/index.ts
|
|
5
|
-
import { clone, enumerate, lowerCaseFirst as lowerCaseFirst3, paramCase, safeJSONStringify } from "@zenstackhq/common-helpers";
|
|
6
|
-
import { ORMError as ORMError2, ORMErrorReason } from "@zenstackhq/orm";
|
|
7
|
-
import { Decimal as Decimal2 } from "decimal.js";
|
|
8
|
-
import SuperJSON3 from "superjson";
|
|
9
|
-
import tsjapi from "ts-japi";
|
|
10
|
-
import { match as match2 } from "ts-pattern";
|
|
11
|
-
import UrlPattern from "url-pattern";
|
|
12
|
-
import z2 from "zod";
|
|
13
|
-
import { fromError } from "zod-validation-error/v4";
|
|
14
|
-
|
|
15
|
-
// src/api/common/procedures.ts
|
|
16
|
-
import { ORMError } from "@zenstackhq/orm";
|
|
17
|
-
var PROCEDURE_ROUTE_PREFIXES = "$procs";
|
|
18
|
-
function getProcedureDef(schema, proc) {
|
|
19
|
-
const procs = schema.procedures ?? {};
|
|
20
|
-
if (!Object.prototype.hasOwnProperty.call(procs, proc)) {
|
|
21
|
-
return void 0;
|
|
22
|
-
}
|
|
23
|
-
return procs[proc];
|
|
24
|
-
}
|
|
25
|
-
__name(getProcedureDef, "getProcedureDef");
|
|
26
|
-
function mapProcedureArgs(procDef, payload) {
|
|
27
|
-
const params = Object.values(procDef.params ?? {});
|
|
28
|
-
if (params.length === 0) {
|
|
29
|
-
if (typeof payload === "undefined") {
|
|
30
|
-
return void 0;
|
|
31
|
-
}
|
|
32
|
-
if (payload && typeof payload === "object" && !Array.isArray(payload)) {
|
|
33
|
-
const envelope2 = payload;
|
|
34
|
-
const argsPayload2 = Object.prototype.hasOwnProperty.call(envelope2, "args") ? envelope2.args : void 0;
|
|
35
|
-
if (typeof argsPayload2 === "undefined") {
|
|
36
|
-
return payload;
|
|
37
|
-
}
|
|
38
|
-
if (argsPayload2 && typeof argsPayload2 === "object" && !Array.isArray(argsPayload2)) {
|
|
39
|
-
if (Object.keys(argsPayload2).length === 0) {
|
|
40
|
-
return payload;
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
throw new Error("procedure does not accept arguments");
|
|
45
|
-
}
|
|
46
|
-
if (typeof payload === "undefined" && params.every((p) => p.optional)) {
|
|
47
|
-
return void 0;
|
|
48
|
-
}
|
|
49
|
-
if (typeof payload === "undefined") {
|
|
50
|
-
throw new Error("missing procedure arguments");
|
|
51
|
-
}
|
|
52
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
53
|
-
throw new Error("procedure payload must be an object");
|
|
54
|
-
}
|
|
55
|
-
const envelope = payload;
|
|
56
|
-
const argsPayload = Object.prototype.hasOwnProperty.call(envelope, "args") ? envelope.args : void 0;
|
|
57
|
-
if (typeof argsPayload === "undefined") {
|
|
58
|
-
if (params.every((p) => p.optional)) {
|
|
59
|
-
return payload;
|
|
60
|
-
}
|
|
61
|
-
throw new Error("missing procedure arguments");
|
|
62
|
-
}
|
|
63
|
-
if (!argsPayload || typeof argsPayload !== "object" || Array.isArray(argsPayload)) {
|
|
64
|
-
throw new Error("procedure `args` must be an object");
|
|
65
|
-
}
|
|
66
|
-
const obj = argsPayload;
|
|
67
|
-
for (const key of Object.keys(obj)) {
|
|
68
|
-
if (!params.some((p) => p.name === key)) {
|
|
69
|
-
throw new Error(`unknown procedure argument: ${key}`);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
for (const p of params) {
|
|
73
|
-
if (!Object.prototype.hasOwnProperty.call(obj, p.name)) {
|
|
74
|
-
if (p.optional) {
|
|
75
|
-
continue;
|
|
76
|
-
}
|
|
77
|
-
throw new Error(`missing procedure argument: ${p.name}`);
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
return payload;
|
|
81
|
-
}
|
|
82
|
-
__name(mapProcedureArgs, "mapProcedureArgs");
|
|
83
|
-
|
|
84
|
-
// src/api/common/schemas.ts
|
|
85
|
-
import z from "zod";
|
|
86
|
-
var loggerSchema = z.union([
|
|
87
|
-
z.enum([
|
|
88
|
-
"debug",
|
|
89
|
-
"info",
|
|
90
|
-
"warn",
|
|
91
|
-
"error"
|
|
92
|
-
]).array(),
|
|
93
|
-
z.function()
|
|
94
|
-
]);
|
|
95
|
-
var fieldSlicingSchema = z.looseObject({
|
|
96
|
-
includedFilterKinds: z.string().array().optional(),
|
|
97
|
-
excludedFilterKinds: z.string().array().optional()
|
|
98
|
-
});
|
|
99
|
-
var modelSlicingSchema = z.looseObject({
|
|
100
|
-
includedOperations: z.array(z.string()).optional(),
|
|
101
|
-
excludedOperations: z.array(z.string()).optional(),
|
|
102
|
-
fields: z.record(z.string(), fieldSlicingSchema).optional()
|
|
103
|
-
});
|
|
104
|
-
var slicingSchema = z.looseObject({
|
|
105
|
-
includedModels: z.array(z.string()).optional(),
|
|
106
|
-
excludedModels: z.array(z.string()).optional(),
|
|
107
|
-
models: z.record(z.string(), modelSlicingSchema).optional(),
|
|
108
|
-
includedProcedures: z.array(z.string()).optional(),
|
|
109
|
-
excludedProcedures: z.array(z.string()).optional()
|
|
110
|
-
});
|
|
111
|
-
var queryOptionsSchema = z.looseObject({
|
|
112
|
-
omit: z.record(z.string(), z.record(z.string(), z.boolean())).optional(),
|
|
113
|
-
slicing: slicingSchema.optional()
|
|
114
|
-
});
|
|
115
|
-
|
|
116
|
-
// src/api/common/utils.ts
|
|
117
|
-
import SuperJSON from "superjson";
|
|
118
|
-
async function processSuperJsonRequestPayload(payload) {
|
|
119
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload) || !("meta" in payload)) {
|
|
120
|
-
return {
|
|
121
|
-
result: payload,
|
|
122
|
-
error: void 0
|
|
123
|
-
};
|
|
124
|
-
}
|
|
125
|
-
const { meta, ...rest } = payload;
|
|
126
|
-
if (meta?.serialization) {
|
|
127
|
-
try {
|
|
128
|
-
return {
|
|
129
|
-
result: SuperJSON.deserialize({
|
|
130
|
-
json: rest,
|
|
131
|
-
meta: meta.serialization
|
|
132
|
-
}),
|
|
133
|
-
error: void 0
|
|
134
|
-
};
|
|
135
|
-
} catch (err) {
|
|
136
|
-
return {
|
|
137
|
-
result: void 0,
|
|
138
|
-
error: `failed to deserialize request payload: ${err.message}`
|
|
139
|
-
};
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
return {
|
|
143
|
-
result: rest,
|
|
144
|
-
error: void 0
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
__name(processSuperJsonRequestPayload, "processSuperJsonRequestPayload");
|
|
148
|
-
function unmarshalQ(value, meta) {
|
|
149
|
-
let parsedValue;
|
|
150
|
-
try {
|
|
151
|
-
parsedValue = JSON.parse(value);
|
|
152
|
-
} catch {
|
|
153
|
-
throw new Error('invalid "q" query parameter');
|
|
154
|
-
}
|
|
155
|
-
if (meta) {
|
|
156
|
-
let parsedMeta;
|
|
157
|
-
try {
|
|
158
|
-
parsedMeta = JSON.parse(meta);
|
|
159
|
-
} catch {
|
|
160
|
-
throw new Error('invalid "meta" query parameter');
|
|
161
|
-
}
|
|
162
|
-
if (parsedMeta.serialization) {
|
|
163
|
-
return SuperJSON.deserialize({
|
|
164
|
-
json: parsedValue,
|
|
165
|
-
meta: parsedMeta.serialization
|
|
166
|
-
});
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
return parsedValue;
|
|
170
|
-
}
|
|
171
|
-
__name(unmarshalQ, "unmarshalQ");
|
|
172
|
-
|
|
173
|
-
// src/api/utils.ts
|
|
174
|
-
import { Decimal } from "decimal.js";
|
|
175
|
-
import SuperJSON2 from "superjson";
|
|
176
|
-
import { match } from "ts-pattern";
|
|
177
|
-
import { fromError as fromError3 } from "zod-validation-error/v3";
|
|
178
|
-
import { fromError as fromError4 } from "zod-validation-error/v4";
|
|
179
|
-
function log(logger, level, message, error) {
|
|
180
|
-
if (!logger) {
|
|
181
|
-
return;
|
|
182
|
-
}
|
|
183
|
-
const getMessage = typeof message === "function" ? message : () => message;
|
|
184
|
-
if (typeof logger === "function") {
|
|
185
|
-
logger(level, getMessage(), error);
|
|
186
|
-
} else if (logger.includes(level)) {
|
|
187
|
-
const logFn = match(level).with("debug", () => console.debug).with("info", () => console.info).with("warn", () => console.warn).with("error", () => console.error).exhaustive();
|
|
188
|
-
logFn(`@zenstackhq/server: [${level}] ${getMessage()}${error ? `
|
|
189
|
-
${error}` : ""}`);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
__name(log, "log");
|
|
193
|
-
function registerCustomSerializers() {
|
|
194
|
-
SuperJSON2.registerCustom({
|
|
195
|
-
isApplicable: /* @__PURE__ */ __name((v) => Decimal.isDecimal(v), "isApplicable"),
|
|
196
|
-
serialize: /* @__PURE__ */ __name((v) => v.toJSON(), "serialize"),
|
|
197
|
-
deserialize: /* @__PURE__ */ __name((v) => new Decimal(v), "deserialize")
|
|
198
|
-
}, "Decimal");
|
|
199
|
-
if (globalThis.Buffer) {
|
|
200
|
-
SuperJSON2.registerCustom({
|
|
201
|
-
isApplicable: /* @__PURE__ */ __name((v) => Buffer.isBuffer(v), "isApplicable"),
|
|
202
|
-
serialize: /* @__PURE__ */ __name((v) => v.toString("base64"), "serialize"),
|
|
203
|
-
deserialize: /* @__PURE__ */ __name((v) => Buffer.from(v, "base64"), "deserialize")
|
|
204
|
-
}, "Bytes");
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
__name(registerCustomSerializers, "registerCustomSerializers");
|
|
208
|
-
function getZodErrorMessage(error) {
|
|
209
|
-
if ("_zod" in error) {
|
|
210
|
-
return fromError4(error).toString();
|
|
211
|
-
} else {
|
|
212
|
-
return fromError3(error).toString();
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
__name(getZodErrorMessage, "getZodErrorMessage");
|
|
216
|
-
|
|
217
|
-
// src/api/rest/openapi.ts
|
|
218
|
-
import { lowerCaseFirst as lowerCaseFirst2 } from "@zenstackhq/common-helpers";
|
|
219
|
-
|
|
220
|
-
// src/api/common/spec-utils.ts
|
|
221
|
-
import { lowerCaseFirst } from "@zenstackhq/common-helpers";
|
|
222
|
-
import { ExpressionUtils } from "@zenstackhq/orm/schema";
|
|
223
|
-
function isModelIncluded(modelName, queryOptions) {
|
|
224
|
-
const slicing = queryOptions?.slicing;
|
|
225
|
-
if (!slicing) return true;
|
|
226
|
-
const excluded = slicing.excludedModels;
|
|
227
|
-
if (excluded?.includes(modelName)) return false;
|
|
228
|
-
const included = slicing.includedModels;
|
|
229
|
-
if (included && !included.includes(modelName)) return false;
|
|
230
|
-
return true;
|
|
231
|
-
}
|
|
232
|
-
__name(isModelIncluded, "isModelIncluded");
|
|
233
|
-
function isOperationIncluded(modelName, op, queryOptions) {
|
|
234
|
-
const slicing = queryOptions?.slicing;
|
|
235
|
-
if (!slicing?.models) return true;
|
|
236
|
-
const modelKey = lowerCaseFirst(modelName);
|
|
237
|
-
const modelSlicing = slicing.models[modelKey] ?? slicing.models.$all;
|
|
238
|
-
if (!modelSlicing) return true;
|
|
239
|
-
const excluded = modelSlicing.excludedOperations;
|
|
240
|
-
if (excluded?.includes(op)) return false;
|
|
241
|
-
const included = modelSlicing.includedOperations;
|
|
242
|
-
if (included && !included.includes(op)) return false;
|
|
243
|
-
return true;
|
|
244
|
-
}
|
|
245
|
-
__name(isOperationIncluded, "isOperationIncluded");
|
|
246
|
-
function isProcedureIncluded(procName, queryOptions) {
|
|
247
|
-
const slicing = queryOptions?.slicing;
|
|
248
|
-
if (!slicing) return true;
|
|
249
|
-
const excluded = slicing.excludedProcedures;
|
|
250
|
-
if (excluded?.includes(procName)) return false;
|
|
251
|
-
const included = slicing.includedProcedures;
|
|
252
|
-
if (included && !included.includes(procName)) return false;
|
|
253
|
-
return true;
|
|
254
|
-
}
|
|
255
|
-
__name(isProcedureIncluded, "isProcedureIncluded");
|
|
256
|
-
function isFieldOmitted(modelName, fieldName, queryOptions) {
|
|
257
|
-
const omit = queryOptions?.omit;
|
|
258
|
-
return omit?.[modelName]?.[fieldName] === true;
|
|
259
|
-
}
|
|
260
|
-
__name(isFieldOmitted, "isFieldOmitted");
|
|
261
|
-
function getIncludedModels(schema, queryOptions) {
|
|
262
|
-
return Object.keys(schema.models).filter((name) => isModelIncluded(name, queryOptions));
|
|
263
|
-
}
|
|
264
|
-
__name(getIncludedModels, "getIncludedModels");
|
|
265
|
-
function isFilterKindIncluded(modelName, fieldName, filterKind, queryOptions) {
|
|
266
|
-
const slicing = queryOptions?.slicing;
|
|
267
|
-
if (!slicing?.models) return true;
|
|
268
|
-
const modelKey = lowerCaseFirst(modelName);
|
|
269
|
-
const modelSlicing = slicing.models[modelKey] ?? slicing.models.$all;
|
|
270
|
-
if (!modelSlicing?.fields) return true;
|
|
271
|
-
const fieldSlicing = modelSlicing.fields[fieldName] ?? modelSlicing.fields.$all;
|
|
272
|
-
if (!fieldSlicing) return true;
|
|
273
|
-
const excluded = fieldSlicing.excludedFilterKinds;
|
|
274
|
-
if (excluded?.includes(filterKind)) return false;
|
|
275
|
-
const included = fieldSlicing.includedFilterKinds;
|
|
276
|
-
if (included && !included.includes(filterKind)) return false;
|
|
277
|
-
return true;
|
|
278
|
-
}
|
|
279
|
-
__name(isFilterKindIncluded, "isFilterKindIncluded");
|
|
280
|
-
function getMetaDescription(attributes) {
|
|
281
|
-
if (!attributes) return void 0;
|
|
282
|
-
for (const attr of attributes) {
|
|
283
|
-
if (attr.name !== "@meta" && attr.name !== "@@meta") continue;
|
|
284
|
-
const nameArg = attr.args?.find((a) => a.name === "name");
|
|
285
|
-
if (!nameArg || ExpressionUtils.getLiteralValue(nameArg.value) !== "description") continue;
|
|
286
|
-
const valueArg = attr.args?.find((a) => a.name === "value");
|
|
287
|
-
if (valueArg) {
|
|
288
|
-
return ExpressionUtils.getLiteralValue(valueArg.value);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
return void 0;
|
|
292
|
-
}
|
|
293
|
-
__name(getMetaDescription, "getMetaDescription");
|
|
294
|
-
|
|
295
|
-
// src/api/rest/openapi.ts
|
|
296
|
-
function errorResponse(description) {
|
|
297
|
-
return {
|
|
298
|
-
description,
|
|
299
|
-
content: {
|
|
300
|
-
"application/vnd.api+json": {
|
|
301
|
-
schema: {
|
|
302
|
-
$ref: "#/components/schemas/_errorResponse"
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
};
|
|
307
|
-
}
|
|
308
|
-
__name(errorResponse, "errorResponse");
|
|
309
|
-
var ERROR_400 = errorResponse("Error occurred while processing the request");
|
|
310
|
-
var ERROR_403 = errorResponse("Forbidden: insufficient permissions to perform this operation");
|
|
311
|
-
var ERROR_404 = errorResponse("Resource not found");
|
|
312
|
-
var ERROR_422 = errorResponse("Operation is unprocessable due to validation errors");
|
|
313
|
-
var SCALAR_STRING_OPS = [
|
|
314
|
-
"$contains",
|
|
315
|
-
"$icontains",
|
|
316
|
-
"$search",
|
|
317
|
-
"$startsWith",
|
|
318
|
-
"$endsWith"
|
|
319
|
-
];
|
|
320
|
-
var SCALAR_COMPARABLE_OPS = [
|
|
321
|
-
"$lt",
|
|
322
|
-
"$lte",
|
|
323
|
-
"$gt",
|
|
324
|
-
"$gte"
|
|
325
|
-
];
|
|
326
|
-
var SCALAR_ARRAY_OPS = [
|
|
327
|
-
"$has",
|
|
328
|
-
"$hasEvery",
|
|
329
|
-
"$hasSome",
|
|
330
|
-
"$isEmpty"
|
|
331
|
-
];
|
|
332
|
-
var RestApiSpecGenerator = class {
|
|
333
|
-
static {
|
|
334
|
-
__name(this, "RestApiSpecGenerator");
|
|
335
|
-
}
|
|
336
|
-
handlerOptions;
|
|
337
|
-
specOptions;
|
|
338
|
-
constructor(handlerOptions) {
|
|
339
|
-
this.handlerOptions = handlerOptions;
|
|
340
|
-
}
|
|
341
|
-
get schema() {
|
|
342
|
-
return this.handlerOptions.schema;
|
|
343
|
-
}
|
|
344
|
-
get modelNameMapping() {
|
|
345
|
-
const mapping = {};
|
|
346
|
-
if (this.handlerOptions.modelNameMapping) {
|
|
347
|
-
for (const [k, v] of Object.entries(this.handlerOptions.modelNameMapping)) {
|
|
348
|
-
mapping[lowerCaseFirst2(k)] = v;
|
|
349
|
-
}
|
|
350
|
-
}
|
|
351
|
-
return mapping;
|
|
352
|
-
}
|
|
353
|
-
get queryOptions() {
|
|
354
|
-
return this.handlerOptions?.queryOptions;
|
|
355
|
-
}
|
|
356
|
-
get nestedRoutes() {
|
|
357
|
-
return this.handlerOptions.nestedRoutes ?? false;
|
|
358
|
-
}
|
|
359
|
-
generateSpec(options) {
|
|
360
|
-
this.specOptions = options;
|
|
361
|
-
return {
|
|
362
|
-
openapi: "3.1.0",
|
|
363
|
-
info: {
|
|
364
|
-
title: options?.title ?? "ZenStack Generated API",
|
|
365
|
-
version: options?.version ?? "1.0.0",
|
|
366
|
-
...options?.description && {
|
|
367
|
-
description: options.description
|
|
368
|
-
},
|
|
369
|
-
...options?.summary && {
|
|
370
|
-
summary: options.summary
|
|
371
|
-
}
|
|
372
|
-
},
|
|
373
|
-
tags: this.generateTags(),
|
|
374
|
-
paths: this.generatePaths(),
|
|
375
|
-
components: {
|
|
376
|
-
schemas: this.generateSchemas(),
|
|
377
|
-
parameters: this.generateSharedParams()
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
}
|
|
381
|
-
generateTags() {
|
|
382
|
-
return getIncludedModels(this.schema, this.queryOptions).map((modelName) => ({
|
|
383
|
-
name: lowerCaseFirst2(modelName),
|
|
384
|
-
description: `${modelName} operations`
|
|
385
|
-
}));
|
|
386
|
-
}
|
|
387
|
-
getModelPath(modelName) {
|
|
388
|
-
const lower = lowerCaseFirst2(modelName);
|
|
389
|
-
return this.modelNameMapping[lower] ?? lower;
|
|
390
|
-
}
|
|
391
|
-
generatePaths() {
|
|
392
|
-
const paths = {};
|
|
393
|
-
for (const modelName of getIncludedModels(this.schema, this.queryOptions)) {
|
|
394
|
-
const modelDef = this.schema.models[modelName];
|
|
395
|
-
const idFields = this.getIdFields(modelDef);
|
|
396
|
-
if (idFields.length === 0) continue;
|
|
397
|
-
const modelPath = this.getModelPath(modelName);
|
|
398
|
-
const tag = lowerCaseFirst2(modelName);
|
|
399
|
-
const collectionPath = this.buildCollectionPath(modelName, modelDef, tag);
|
|
400
|
-
if (Object.keys(collectionPath).length > 0) {
|
|
401
|
-
paths[`/${modelPath}`] = collectionPath;
|
|
402
|
-
}
|
|
403
|
-
const singlePath = this.buildSinglePath(modelDef, tag);
|
|
404
|
-
if (Object.keys(singlePath).length > 0) {
|
|
405
|
-
paths[`/${modelPath}/{id}`] = singlePath;
|
|
406
|
-
}
|
|
407
|
-
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
408
|
-
if (!fieldDef.relation) continue;
|
|
409
|
-
if (!isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
410
|
-
const relModelDef = this.schema.models[fieldDef.type];
|
|
411
|
-
if (!relModelDef) continue;
|
|
412
|
-
const relIdFields = this.getIdFields(relModelDef);
|
|
413
|
-
if (relIdFields.length === 0) continue;
|
|
414
|
-
paths[`/${modelPath}/{id}/${fieldName}`] = this.buildRelatedPath(modelName, fieldName, fieldDef, tag);
|
|
415
|
-
if (this.nestedRoutes && fieldDef.array) {
|
|
416
|
-
const nestedSinglePath = this.buildNestedSinglePath(modelName, fieldName, fieldDef, relModelDef, tag);
|
|
417
|
-
if (Object.keys(nestedSinglePath).length > 0) {
|
|
418
|
-
paths[`/${modelPath}/{id}/${fieldName}/{childId}`] = nestedSinglePath;
|
|
419
|
-
}
|
|
420
|
-
}
|
|
421
|
-
paths[`/${modelPath}/{id}/relationships/${fieldName}`] = this.buildRelationshipPath(modelDef, fieldName, fieldDef, tag);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
if (this.schema.procedures) {
|
|
425
|
-
for (const [procName, procDef] of Object.entries(this.schema.procedures)) {
|
|
426
|
-
if (!isProcedureIncluded(procName, this.queryOptions)) continue;
|
|
427
|
-
const isMutation = !!procDef.mutation;
|
|
428
|
-
if (isMutation) {
|
|
429
|
-
paths[`/${PROCEDURE_ROUTE_PREFIXES}/${procName}`] = {
|
|
430
|
-
post: this.buildProcedureOperation(procName, "post")
|
|
431
|
-
};
|
|
432
|
-
} else {
|
|
433
|
-
paths[`/${PROCEDURE_ROUTE_PREFIXES}/${procName}`] = {
|
|
434
|
-
get: this.buildProcedureOperation(procName, "get")
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
}
|
|
439
|
-
return paths;
|
|
440
|
-
}
|
|
441
|
-
buildCollectionPath(modelName, modelDef, tag) {
|
|
442
|
-
const filterParams = this.buildFilterParams(modelName, modelDef);
|
|
443
|
-
const listOp = {
|
|
444
|
-
tags: [
|
|
445
|
-
tag
|
|
446
|
-
],
|
|
447
|
-
summary: `List ${modelName} resources`,
|
|
448
|
-
operationId: `list${modelName}`,
|
|
449
|
-
parameters: [
|
|
450
|
-
{
|
|
451
|
-
$ref: "#/components/parameters/include"
|
|
452
|
-
},
|
|
453
|
-
{
|
|
454
|
-
$ref: "#/components/parameters/sort"
|
|
455
|
-
},
|
|
456
|
-
{
|
|
457
|
-
$ref: "#/components/parameters/pageOffset"
|
|
458
|
-
},
|
|
459
|
-
{
|
|
460
|
-
$ref: "#/components/parameters/pageLimit"
|
|
461
|
-
},
|
|
462
|
-
...filterParams
|
|
463
|
-
],
|
|
464
|
-
responses: {
|
|
465
|
-
"200": {
|
|
466
|
-
description: `List of ${modelName} resources`,
|
|
467
|
-
content: {
|
|
468
|
-
"application/vnd.api+json": {
|
|
469
|
-
schema: {
|
|
470
|
-
$ref: `#/components/schemas/${modelName}ListResponse`
|
|
471
|
-
}
|
|
472
|
-
}
|
|
473
|
-
}
|
|
474
|
-
},
|
|
475
|
-
"400": ERROR_400
|
|
476
|
-
}
|
|
477
|
-
};
|
|
478
|
-
const createOp = {
|
|
479
|
-
tags: [
|
|
480
|
-
tag
|
|
481
|
-
],
|
|
482
|
-
summary: `Create a ${modelName} resource`,
|
|
483
|
-
operationId: `create${modelName}`,
|
|
484
|
-
requestBody: {
|
|
485
|
-
required: true,
|
|
486
|
-
content: {
|
|
487
|
-
"application/vnd.api+json": {
|
|
488
|
-
schema: {
|
|
489
|
-
$ref: `#/components/schemas/${modelName}CreateRequest`
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
},
|
|
494
|
-
responses: {
|
|
495
|
-
"201": {
|
|
496
|
-
description: `Created ${modelName} resource`,
|
|
497
|
-
content: {
|
|
498
|
-
"application/vnd.api+json": {
|
|
499
|
-
schema: {
|
|
500
|
-
$ref: `#/components/schemas/${modelName}Response`
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
|
-
},
|
|
505
|
-
"400": ERROR_400,
|
|
506
|
-
...this.mayDenyAccess(modelDef, "create") && {
|
|
507
|
-
"403": ERROR_403
|
|
508
|
-
},
|
|
509
|
-
"422": ERROR_422
|
|
510
|
-
}
|
|
511
|
-
};
|
|
512
|
-
const result = {};
|
|
513
|
-
if (isOperationIncluded(modelName, "findMany", this.queryOptions)) {
|
|
514
|
-
result["get"] = listOp;
|
|
515
|
-
}
|
|
516
|
-
if (isOperationIncluded(modelName, "create", this.queryOptions)) {
|
|
517
|
-
result["post"] = createOp;
|
|
518
|
-
}
|
|
519
|
-
return result;
|
|
520
|
-
}
|
|
521
|
-
buildSinglePath(modelDef, tag) {
|
|
522
|
-
const modelName = modelDef.name;
|
|
523
|
-
const idParam = {
|
|
524
|
-
$ref: "#/components/parameters/id"
|
|
525
|
-
};
|
|
526
|
-
const result = {};
|
|
527
|
-
if (isOperationIncluded(modelName, "findUnique", this.queryOptions)) {
|
|
528
|
-
result["get"] = {
|
|
529
|
-
tags: [
|
|
530
|
-
tag
|
|
531
|
-
],
|
|
532
|
-
summary: `Get a ${modelName} resource by ID`,
|
|
533
|
-
operationId: `get${modelName}`,
|
|
534
|
-
parameters: [
|
|
535
|
-
idParam,
|
|
536
|
-
{
|
|
537
|
-
$ref: "#/components/parameters/include"
|
|
538
|
-
}
|
|
539
|
-
],
|
|
540
|
-
responses: {
|
|
541
|
-
"200": {
|
|
542
|
-
description: `${modelName} resource`,
|
|
543
|
-
content: {
|
|
544
|
-
"application/vnd.api+json": {
|
|
545
|
-
schema: {
|
|
546
|
-
$ref: `#/components/schemas/${modelName}Response`
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
},
|
|
551
|
-
"404": ERROR_404
|
|
552
|
-
}
|
|
553
|
-
};
|
|
554
|
-
}
|
|
555
|
-
if (isOperationIncluded(modelName, "update", this.queryOptions)) {
|
|
556
|
-
result["patch"] = {
|
|
557
|
-
tags: [
|
|
558
|
-
tag
|
|
559
|
-
],
|
|
560
|
-
summary: `Update a ${modelName} resource`,
|
|
561
|
-
operationId: `update${modelName}`,
|
|
562
|
-
parameters: [
|
|
563
|
-
idParam
|
|
564
|
-
],
|
|
565
|
-
requestBody: {
|
|
566
|
-
required: true,
|
|
567
|
-
content: {
|
|
568
|
-
"application/vnd.api+json": {
|
|
569
|
-
schema: {
|
|
570
|
-
$ref: `#/components/schemas/${modelName}UpdateRequest`
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
},
|
|
575
|
-
responses: {
|
|
576
|
-
"200": {
|
|
577
|
-
description: `Updated ${modelName} resource`,
|
|
578
|
-
content: {
|
|
579
|
-
"application/vnd.api+json": {
|
|
580
|
-
schema: {
|
|
581
|
-
$ref: `#/components/schemas/${modelName}Response`
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
},
|
|
586
|
-
"400": ERROR_400,
|
|
587
|
-
...this.mayDenyAccess(modelDef, "update") && {
|
|
588
|
-
"403": ERROR_403
|
|
589
|
-
},
|
|
590
|
-
"404": ERROR_404,
|
|
591
|
-
"422": ERROR_422
|
|
592
|
-
}
|
|
593
|
-
};
|
|
594
|
-
}
|
|
595
|
-
if (isOperationIncluded(modelName, "delete", this.queryOptions)) {
|
|
596
|
-
result["delete"] = {
|
|
597
|
-
tags: [
|
|
598
|
-
tag
|
|
599
|
-
],
|
|
600
|
-
summary: `Delete a ${modelName} resource`,
|
|
601
|
-
operationId: `delete${modelName}`,
|
|
602
|
-
parameters: [
|
|
603
|
-
idParam
|
|
604
|
-
],
|
|
605
|
-
responses: {
|
|
606
|
-
"200": {
|
|
607
|
-
description: "Deleted successfully"
|
|
608
|
-
},
|
|
609
|
-
...this.mayDenyAccess(modelDef, "delete") && {
|
|
610
|
-
"403": ERROR_403
|
|
611
|
-
},
|
|
612
|
-
"404": ERROR_404
|
|
613
|
-
}
|
|
614
|
-
};
|
|
615
|
-
}
|
|
616
|
-
return result;
|
|
617
|
-
}
|
|
618
|
-
buildRelatedPath(modelName, fieldName, fieldDef, tag) {
|
|
619
|
-
const isCollection = !!fieldDef.array;
|
|
620
|
-
const relModelDef = this.schema.models[fieldDef.type];
|
|
621
|
-
const params = [
|
|
622
|
-
{
|
|
623
|
-
$ref: "#/components/parameters/id"
|
|
624
|
-
},
|
|
625
|
-
{
|
|
626
|
-
$ref: "#/components/parameters/include"
|
|
627
|
-
}
|
|
628
|
-
];
|
|
629
|
-
if (isCollection && relModelDef) {
|
|
630
|
-
params.push({
|
|
631
|
-
$ref: "#/components/parameters/sort"
|
|
632
|
-
}, {
|
|
633
|
-
$ref: "#/components/parameters/pageOffset"
|
|
634
|
-
}, {
|
|
635
|
-
$ref: "#/components/parameters/pageLimit"
|
|
636
|
-
}, ...this.buildFilterParams(fieldDef.type, relModelDef));
|
|
637
|
-
}
|
|
638
|
-
const pathItem = {
|
|
639
|
-
get: {
|
|
640
|
-
tags: [
|
|
641
|
-
tag
|
|
642
|
-
],
|
|
643
|
-
summary: `Fetch related ${fieldDef.type} for ${modelName}`,
|
|
644
|
-
operationId: `get${modelName}_${fieldName}`,
|
|
645
|
-
parameters: params,
|
|
646
|
-
responses: {
|
|
647
|
-
"200": {
|
|
648
|
-
description: `Related ${fieldDef.type} resource(s)`,
|
|
649
|
-
content: {
|
|
650
|
-
"application/vnd.api+json": {
|
|
651
|
-
schema: isCollection ? {
|
|
652
|
-
$ref: `#/components/schemas/${fieldDef.type}ListResponse`
|
|
653
|
-
} : {
|
|
654
|
-
$ref: `#/components/schemas/${fieldDef.type}Response`
|
|
655
|
-
}
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
},
|
|
659
|
-
"404": ERROR_404
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
};
|
|
663
|
-
if (this.nestedRoutes && relModelDef) {
|
|
664
|
-
const mayDeny = this.mayDenyAccess(relModelDef, isCollection ? "create" : "update");
|
|
665
|
-
if (isCollection && isOperationIncluded(fieldDef.type, "create", this.queryOptions)) {
|
|
666
|
-
pathItem["post"] = {
|
|
667
|
-
tags: [
|
|
668
|
-
tag
|
|
669
|
-
],
|
|
670
|
-
summary: `Create a nested ${fieldDef.type} under ${modelName}`,
|
|
671
|
-
operationId: `create${modelName}_${fieldName}`,
|
|
672
|
-
parameters: [
|
|
673
|
-
{
|
|
674
|
-
$ref: "#/components/parameters/id"
|
|
675
|
-
}
|
|
676
|
-
],
|
|
677
|
-
requestBody: {
|
|
678
|
-
required: true,
|
|
679
|
-
content: {
|
|
680
|
-
"application/vnd.api+json": {
|
|
681
|
-
schema: {
|
|
682
|
-
$ref: `#/components/schemas/${fieldDef.type}CreateRequest`
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
},
|
|
687
|
-
responses: {
|
|
688
|
-
"201": {
|
|
689
|
-
description: `Created ${fieldDef.type} resource`,
|
|
690
|
-
content: {
|
|
691
|
-
"application/vnd.api+json": {
|
|
692
|
-
schema: {
|
|
693
|
-
$ref: `#/components/schemas/${fieldDef.type}Response`
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
}
|
|
697
|
-
},
|
|
698
|
-
"400": ERROR_400,
|
|
699
|
-
...mayDeny && {
|
|
700
|
-
"403": ERROR_403
|
|
701
|
-
},
|
|
702
|
-
"422": ERROR_422
|
|
703
|
-
}
|
|
704
|
-
};
|
|
705
|
-
} else if (!isCollection && isOperationIncluded(fieldDef.type, "update", this.queryOptions)) {
|
|
706
|
-
pathItem["patch"] = {
|
|
707
|
-
tags: [
|
|
708
|
-
tag
|
|
709
|
-
],
|
|
710
|
-
summary: `Update nested ${fieldDef.type} under ${modelName}`,
|
|
711
|
-
operationId: `update${modelName}_${fieldName}`,
|
|
712
|
-
parameters: [
|
|
713
|
-
{
|
|
714
|
-
$ref: "#/components/parameters/id"
|
|
715
|
-
}
|
|
716
|
-
],
|
|
717
|
-
requestBody: {
|
|
718
|
-
required: true,
|
|
719
|
-
content: {
|
|
720
|
-
"application/vnd.api+json": {
|
|
721
|
-
schema: {
|
|
722
|
-
$ref: `#/components/schemas/${fieldDef.type}UpdateRequest`
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
}
|
|
726
|
-
},
|
|
727
|
-
responses: {
|
|
728
|
-
"200": {
|
|
729
|
-
description: `Updated ${fieldDef.type} resource`,
|
|
730
|
-
content: {
|
|
731
|
-
"application/vnd.api+json": {
|
|
732
|
-
schema: {
|
|
733
|
-
$ref: `#/components/schemas/${fieldDef.type}Response`
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
},
|
|
738
|
-
"400": ERROR_400,
|
|
739
|
-
...mayDeny && {
|
|
740
|
-
"403": ERROR_403
|
|
741
|
-
},
|
|
742
|
-
"404": ERROR_404,
|
|
743
|
-
"422": ERROR_422
|
|
744
|
-
}
|
|
745
|
-
};
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
return pathItem;
|
|
749
|
-
}
|
|
750
|
-
buildNestedSinglePath(modelName, fieldName, fieldDef, relModelDef, tag) {
|
|
751
|
-
const childIdParam = {
|
|
752
|
-
name: "childId",
|
|
753
|
-
in: "path",
|
|
754
|
-
required: true,
|
|
755
|
-
schema: {
|
|
756
|
-
type: "string"
|
|
757
|
-
}
|
|
758
|
-
};
|
|
759
|
-
const idParam = {
|
|
760
|
-
$ref: "#/components/parameters/id"
|
|
761
|
-
};
|
|
762
|
-
const mayDenyUpdate = this.mayDenyAccess(relModelDef, "update");
|
|
763
|
-
const mayDenyDelete = this.mayDenyAccess(relModelDef, "delete");
|
|
764
|
-
const result = {};
|
|
765
|
-
if (isOperationIncluded(fieldDef.type, "findUnique", this.queryOptions)) {
|
|
766
|
-
result["get"] = {
|
|
767
|
-
tags: [
|
|
768
|
-
tag
|
|
769
|
-
],
|
|
770
|
-
summary: `Get a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
771
|
-
operationId: `get${modelName}_${fieldName}_single`,
|
|
772
|
-
parameters: [
|
|
773
|
-
idParam,
|
|
774
|
-
childIdParam,
|
|
775
|
-
{
|
|
776
|
-
$ref: "#/components/parameters/include"
|
|
777
|
-
}
|
|
778
|
-
],
|
|
779
|
-
responses: {
|
|
780
|
-
"200": {
|
|
781
|
-
description: `${fieldDef.type} resource`,
|
|
782
|
-
content: {
|
|
783
|
-
"application/vnd.api+json": {
|
|
784
|
-
schema: {
|
|
785
|
-
$ref: `#/components/schemas/${fieldDef.type}Response`
|
|
786
|
-
}
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
},
|
|
790
|
-
"404": ERROR_404
|
|
791
|
-
}
|
|
792
|
-
};
|
|
793
|
-
}
|
|
794
|
-
if (isOperationIncluded(fieldDef.type, "update", this.queryOptions)) {
|
|
795
|
-
result["patch"] = {
|
|
796
|
-
tags: [
|
|
797
|
-
tag
|
|
798
|
-
],
|
|
799
|
-
summary: `Update a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
800
|
-
operationId: `update${modelName}_${fieldName}_single`,
|
|
801
|
-
parameters: [
|
|
802
|
-
idParam,
|
|
803
|
-
childIdParam
|
|
804
|
-
],
|
|
805
|
-
requestBody: {
|
|
806
|
-
required: true,
|
|
807
|
-
content: {
|
|
808
|
-
"application/vnd.api+json": {
|
|
809
|
-
schema: {
|
|
810
|
-
$ref: `#/components/schemas/${fieldDef.type}UpdateRequest`
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
}
|
|
814
|
-
},
|
|
815
|
-
responses: {
|
|
816
|
-
"200": {
|
|
817
|
-
description: `Updated ${fieldDef.type} resource`,
|
|
818
|
-
content: {
|
|
819
|
-
"application/vnd.api+json": {
|
|
820
|
-
schema: {
|
|
821
|
-
$ref: `#/components/schemas/${fieldDef.type}Response`
|
|
822
|
-
}
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
},
|
|
826
|
-
"400": ERROR_400,
|
|
827
|
-
...mayDenyUpdate && {
|
|
828
|
-
"403": ERROR_403
|
|
829
|
-
},
|
|
830
|
-
"404": ERROR_404,
|
|
831
|
-
"422": ERROR_422
|
|
832
|
-
}
|
|
833
|
-
};
|
|
834
|
-
}
|
|
835
|
-
if (isOperationIncluded(fieldDef.type, "delete", this.queryOptions)) {
|
|
836
|
-
result["delete"] = {
|
|
837
|
-
tags: [
|
|
838
|
-
tag
|
|
839
|
-
],
|
|
840
|
-
summary: `Delete a nested ${fieldDef.type} by ID under ${modelName}`,
|
|
841
|
-
operationId: `delete${modelName}_${fieldName}_single`,
|
|
842
|
-
parameters: [
|
|
843
|
-
idParam,
|
|
844
|
-
childIdParam
|
|
845
|
-
],
|
|
846
|
-
responses: {
|
|
847
|
-
"200": {
|
|
848
|
-
description: "Deleted successfully"
|
|
849
|
-
},
|
|
850
|
-
...mayDenyDelete && {
|
|
851
|
-
"403": ERROR_403
|
|
852
|
-
},
|
|
853
|
-
"404": ERROR_404
|
|
854
|
-
}
|
|
855
|
-
};
|
|
856
|
-
}
|
|
857
|
-
return result;
|
|
858
|
-
}
|
|
859
|
-
buildRelationshipPath(modelDef, fieldName, fieldDef, tag) {
|
|
860
|
-
const modelName = modelDef.name;
|
|
861
|
-
const isCollection = !!fieldDef.array;
|
|
862
|
-
const idParam = {
|
|
863
|
-
$ref: "#/components/parameters/id"
|
|
864
|
-
};
|
|
865
|
-
const relSchemaRef = isCollection ? {
|
|
866
|
-
$ref: "#/components/schemas/_toManyRelationshipWithLinks"
|
|
867
|
-
} : {
|
|
868
|
-
$ref: "#/components/schemas/_toOneRelationshipWithLinks"
|
|
869
|
-
};
|
|
870
|
-
const relRequestRef = isCollection ? {
|
|
871
|
-
$ref: "#/components/schemas/_toManyRelationshipRequest"
|
|
872
|
-
} : {
|
|
873
|
-
$ref: "#/components/schemas/_toOneRelationshipRequest"
|
|
874
|
-
};
|
|
875
|
-
const mayDeny = this.mayDenyAccess(modelDef, "update");
|
|
876
|
-
const pathItem = {
|
|
877
|
-
get: {
|
|
878
|
-
tags: [
|
|
879
|
-
tag
|
|
880
|
-
],
|
|
881
|
-
summary: `Fetch ${fieldName} relationship`,
|
|
882
|
-
operationId: `get${modelName}_relationships_${fieldName}`,
|
|
883
|
-
parameters: [
|
|
884
|
-
idParam
|
|
885
|
-
],
|
|
886
|
-
responses: {
|
|
887
|
-
"200": {
|
|
888
|
-
description: `${fieldName} relationship`,
|
|
889
|
-
content: {
|
|
890
|
-
"application/vnd.api+json": {
|
|
891
|
-
schema: relSchemaRef
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
},
|
|
895
|
-
"404": ERROR_404
|
|
896
|
-
}
|
|
897
|
-
},
|
|
898
|
-
put: {
|
|
899
|
-
tags: [
|
|
900
|
-
tag
|
|
901
|
-
],
|
|
902
|
-
summary: `Replace ${fieldName} relationship`,
|
|
903
|
-
operationId: `put${modelName}_relationships_${fieldName}`,
|
|
904
|
-
parameters: [
|
|
905
|
-
idParam
|
|
906
|
-
],
|
|
907
|
-
requestBody: {
|
|
908
|
-
required: true,
|
|
909
|
-
content: {
|
|
910
|
-
"application/vnd.api+json": {
|
|
911
|
-
schema: relRequestRef
|
|
912
|
-
}
|
|
913
|
-
}
|
|
914
|
-
},
|
|
915
|
-
responses: {
|
|
916
|
-
"200": {
|
|
917
|
-
description: "Relationship updated"
|
|
918
|
-
},
|
|
919
|
-
"400": ERROR_400,
|
|
920
|
-
...mayDeny && {
|
|
921
|
-
"403": ERROR_403
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
},
|
|
925
|
-
patch: {
|
|
926
|
-
tags: [
|
|
927
|
-
tag
|
|
928
|
-
],
|
|
929
|
-
summary: `Update ${fieldName} relationship`,
|
|
930
|
-
operationId: `patch${modelName}_relationships_${fieldName}`,
|
|
931
|
-
parameters: [
|
|
932
|
-
idParam
|
|
933
|
-
],
|
|
934
|
-
requestBody: {
|
|
935
|
-
required: true,
|
|
936
|
-
content: {
|
|
937
|
-
"application/vnd.api+json": {
|
|
938
|
-
schema: relRequestRef
|
|
939
|
-
}
|
|
940
|
-
}
|
|
941
|
-
},
|
|
942
|
-
responses: {
|
|
943
|
-
"200": {
|
|
944
|
-
description: "Relationship updated"
|
|
945
|
-
},
|
|
946
|
-
"400": ERROR_400,
|
|
947
|
-
...mayDeny && {
|
|
948
|
-
"403": ERROR_403
|
|
949
|
-
}
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
};
|
|
953
|
-
if (isCollection) {
|
|
954
|
-
pathItem["post"] = {
|
|
955
|
-
tags: [
|
|
956
|
-
tag
|
|
957
|
-
],
|
|
958
|
-
summary: `Add to ${fieldName} collection relationship`,
|
|
959
|
-
operationId: `post${modelName}_relationships_${fieldName}`,
|
|
960
|
-
parameters: [
|
|
961
|
-
idParam
|
|
962
|
-
],
|
|
963
|
-
requestBody: {
|
|
964
|
-
required: true,
|
|
965
|
-
content: {
|
|
966
|
-
"application/vnd.api+json": {
|
|
967
|
-
schema: {
|
|
968
|
-
$ref: "#/components/schemas/_toManyRelationshipRequest"
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
},
|
|
973
|
-
responses: {
|
|
974
|
-
"200": {
|
|
975
|
-
description: "Added to relationship collection"
|
|
976
|
-
},
|
|
977
|
-
"400": ERROR_400,
|
|
978
|
-
...mayDeny && {
|
|
979
|
-
"403": ERROR_403
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
|
-
return pathItem;
|
|
985
|
-
}
|
|
986
|
-
buildProcedureOperation(procName, method) {
|
|
987
|
-
const op = {
|
|
988
|
-
tags: [
|
|
989
|
-
"$procs"
|
|
990
|
-
],
|
|
991
|
-
summary: `Execute procedure ${procName}`,
|
|
992
|
-
operationId: `proc_${procName}`,
|
|
993
|
-
responses: {
|
|
994
|
-
"200": {
|
|
995
|
-
description: `Result of ${procName}`
|
|
996
|
-
},
|
|
997
|
-
"400": ERROR_400
|
|
998
|
-
}
|
|
999
|
-
};
|
|
1000
|
-
if (method === "get") {
|
|
1001
|
-
op["parameters"] = [
|
|
1002
|
-
{
|
|
1003
|
-
name: "q",
|
|
1004
|
-
in: "query",
|
|
1005
|
-
description: "Procedure arguments as JSON",
|
|
1006
|
-
schema: {
|
|
1007
|
-
type: "string"
|
|
1008
|
-
}
|
|
1009
|
-
}
|
|
1010
|
-
];
|
|
1011
|
-
} else {
|
|
1012
|
-
op["requestBody"] = {
|
|
1013
|
-
content: {
|
|
1014
|
-
"application/json": {
|
|
1015
|
-
schema: {
|
|
1016
|
-
type: "object"
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
};
|
|
1021
|
-
}
|
|
1022
|
-
return op;
|
|
1023
|
-
}
|
|
1024
|
-
buildFilterParams(modelName, modelDef) {
|
|
1025
|
-
const params = [];
|
|
1026
|
-
const idFieldNames = new Set(modelDef.idFields);
|
|
1027
|
-
if (isFilterKindIncluded(modelName, "id", "Equality", this.queryOptions)) {
|
|
1028
|
-
params.push({
|
|
1029
|
-
name: "filter[id]",
|
|
1030
|
-
in: "query",
|
|
1031
|
-
schema: {
|
|
1032
|
-
type: "string"
|
|
1033
|
-
},
|
|
1034
|
-
description: `Filter by ${modelName} ID`
|
|
1035
|
-
});
|
|
1036
|
-
}
|
|
1037
|
-
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
1038
|
-
if (fieldDef.relation) continue;
|
|
1039
|
-
if (idFieldNames.has(fieldName)) continue;
|
|
1040
|
-
const type = fieldDef.type;
|
|
1041
|
-
if (isFilterKindIncluded(modelName, fieldName, "Equality", this.queryOptions)) {
|
|
1042
|
-
params.push({
|
|
1043
|
-
name: `filter[${fieldName}]`,
|
|
1044
|
-
in: "query",
|
|
1045
|
-
schema: {
|
|
1046
|
-
type: "string"
|
|
1047
|
-
},
|
|
1048
|
-
description: `Filter by ${fieldName}`
|
|
1049
|
-
});
|
|
1050
|
-
}
|
|
1051
|
-
if (type === "String" && isFilterKindIncluded(modelName, fieldName, "Like", this.queryOptions)) {
|
|
1052
|
-
for (const op of SCALAR_STRING_OPS) {
|
|
1053
|
-
params.push({
|
|
1054
|
-
name: `filter[${fieldName}][${op}]`,
|
|
1055
|
-
in: "query",
|
|
1056
|
-
schema: {
|
|
1057
|
-
type: "string"
|
|
1058
|
-
}
|
|
1059
|
-
});
|
|
1060
|
-
}
|
|
1061
|
-
} else if ((type === "Int" || type === "Float" || type === "BigInt" || type === "Decimal" || type === "DateTime") && isFilterKindIncluded(modelName, fieldName, "Range", this.queryOptions)) {
|
|
1062
|
-
for (const op of SCALAR_COMPARABLE_OPS) {
|
|
1063
|
-
params.push({
|
|
1064
|
-
name: `filter[${fieldName}][${op}]`,
|
|
1065
|
-
in: "query",
|
|
1066
|
-
schema: {
|
|
1067
|
-
type: "string"
|
|
1068
|
-
}
|
|
1069
|
-
});
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
if (fieldDef.array && isFilterKindIncluded(modelName, fieldName, "List", this.queryOptions)) {
|
|
1073
|
-
for (const op of SCALAR_ARRAY_OPS) {
|
|
1074
|
-
params.push({
|
|
1075
|
-
name: `filter[${fieldName}][${op}]`,
|
|
1076
|
-
in: "query",
|
|
1077
|
-
schema: {
|
|
1078
|
-
type: "string"
|
|
1079
|
-
}
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
}
|
|
1083
|
-
}
|
|
1084
|
-
return params;
|
|
1085
|
-
}
|
|
1086
|
-
generateSchemas() {
|
|
1087
|
-
const schemas = {};
|
|
1088
|
-
Object.assign(schemas, this.buildSharedSchemas());
|
|
1089
|
-
if (this.schema.enums) {
|
|
1090
|
-
for (const [_enumName, enumDef] of Object.entries(this.schema.enums)) {
|
|
1091
|
-
schemas[_enumName] = this.buildEnumSchema(enumDef);
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
if (this.schema.typeDefs) {
|
|
1095
|
-
for (const [typeName, typeDef] of Object.entries(this.schema.typeDefs)) {
|
|
1096
|
-
schemas[typeName] = this.buildTypeDefSchema(typeDef);
|
|
1097
|
-
}
|
|
1098
|
-
}
|
|
1099
|
-
for (const modelName of getIncludedModels(this.schema, this.queryOptions)) {
|
|
1100
|
-
const modelDef = this.schema.models[modelName];
|
|
1101
|
-
const idFields = this.getIdFields(modelDef);
|
|
1102
|
-
if (idFields.length === 0) continue;
|
|
1103
|
-
schemas[modelName] = this.buildModelReadSchema(modelName, modelDef);
|
|
1104
|
-
schemas[`${modelName}CreateRequest`] = this.buildCreateRequestSchema(modelName, modelDef);
|
|
1105
|
-
schemas[`${modelName}UpdateRequest`] = this.buildUpdateRequestSchema(modelDef);
|
|
1106
|
-
schemas[`${modelName}Response`] = this.buildModelResponseSchema(modelName);
|
|
1107
|
-
schemas[`${modelName}ListResponse`] = this.buildModelListResponseSchema(modelName);
|
|
1108
|
-
}
|
|
1109
|
-
return schemas;
|
|
1110
|
-
}
|
|
1111
|
-
buildSharedSchemas() {
|
|
1112
|
-
const nullableString = {
|
|
1113
|
-
oneOf: [
|
|
1114
|
-
{
|
|
1115
|
-
type: "string"
|
|
1116
|
-
},
|
|
1117
|
-
{
|
|
1118
|
-
type: "null"
|
|
1119
|
-
}
|
|
1120
|
-
]
|
|
1121
|
-
};
|
|
1122
|
-
return {
|
|
1123
|
-
_jsonapi: {
|
|
1124
|
-
type: "object",
|
|
1125
|
-
properties: {
|
|
1126
|
-
version: {
|
|
1127
|
-
type: "string"
|
|
1128
|
-
},
|
|
1129
|
-
meta: {
|
|
1130
|
-
type: "object"
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
},
|
|
1134
|
-
_meta: {
|
|
1135
|
-
type: "object",
|
|
1136
|
-
additionalProperties: true
|
|
1137
|
-
},
|
|
1138
|
-
_links: {
|
|
1139
|
-
type: "object",
|
|
1140
|
-
properties: {
|
|
1141
|
-
self: {
|
|
1142
|
-
type: "string"
|
|
1143
|
-
},
|
|
1144
|
-
related: {
|
|
1145
|
-
type: "string"
|
|
1146
|
-
}
|
|
1147
|
-
}
|
|
1148
|
-
},
|
|
1149
|
-
_pagination: {
|
|
1150
|
-
type: "object",
|
|
1151
|
-
properties: {
|
|
1152
|
-
first: nullableString,
|
|
1153
|
-
last: nullableString,
|
|
1154
|
-
prev: nullableString,
|
|
1155
|
-
next: nullableString
|
|
1156
|
-
}
|
|
1157
|
-
},
|
|
1158
|
-
_errors: {
|
|
1159
|
-
type: "array",
|
|
1160
|
-
items: {
|
|
1161
|
-
type: "object",
|
|
1162
|
-
properties: {
|
|
1163
|
-
status: {
|
|
1164
|
-
type: "integer"
|
|
1165
|
-
},
|
|
1166
|
-
code: {
|
|
1167
|
-
type: "string"
|
|
1168
|
-
},
|
|
1169
|
-
title: {
|
|
1170
|
-
type: "string"
|
|
1171
|
-
},
|
|
1172
|
-
detail: {
|
|
1173
|
-
type: "string"
|
|
1174
|
-
}
|
|
1175
|
-
},
|
|
1176
|
-
required: [
|
|
1177
|
-
"status",
|
|
1178
|
-
"title"
|
|
1179
|
-
]
|
|
1180
|
-
}
|
|
1181
|
-
},
|
|
1182
|
-
_errorResponse: {
|
|
1183
|
-
type: "object",
|
|
1184
|
-
properties: {
|
|
1185
|
-
errors: {
|
|
1186
|
-
$ref: "#/components/schemas/_errors"
|
|
1187
|
-
}
|
|
1188
|
-
},
|
|
1189
|
-
required: [
|
|
1190
|
-
"errors"
|
|
1191
|
-
]
|
|
1192
|
-
},
|
|
1193
|
-
_resourceIdentifier: {
|
|
1194
|
-
type: "object",
|
|
1195
|
-
properties: {
|
|
1196
|
-
type: {
|
|
1197
|
-
type: "string"
|
|
1198
|
-
},
|
|
1199
|
-
id: {
|
|
1200
|
-
type: "string"
|
|
1201
|
-
}
|
|
1202
|
-
},
|
|
1203
|
-
required: [
|
|
1204
|
-
"type",
|
|
1205
|
-
"id"
|
|
1206
|
-
]
|
|
1207
|
-
},
|
|
1208
|
-
_resource: {
|
|
1209
|
-
type: "object",
|
|
1210
|
-
properties: {
|
|
1211
|
-
type: {
|
|
1212
|
-
type: "string"
|
|
1213
|
-
},
|
|
1214
|
-
id: {
|
|
1215
|
-
type: "string"
|
|
1216
|
-
},
|
|
1217
|
-
attributes: {
|
|
1218
|
-
type: "object"
|
|
1219
|
-
},
|
|
1220
|
-
relationships: {
|
|
1221
|
-
type: "object"
|
|
1222
|
-
},
|
|
1223
|
-
links: {
|
|
1224
|
-
$ref: "#/components/schemas/_links"
|
|
1225
|
-
},
|
|
1226
|
-
meta: {
|
|
1227
|
-
$ref: "#/components/schemas/_meta"
|
|
1228
|
-
}
|
|
1229
|
-
},
|
|
1230
|
-
required: [
|
|
1231
|
-
"type",
|
|
1232
|
-
"id"
|
|
1233
|
-
]
|
|
1234
|
-
},
|
|
1235
|
-
_relationLinks: {
|
|
1236
|
-
type: "object",
|
|
1237
|
-
properties: {
|
|
1238
|
-
self: {
|
|
1239
|
-
type: "string"
|
|
1240
|
-
},
|
|
1241
|
-
related: {
|
|
1242
|
-
type: "string"
|
|
1243
|
-
}
|
|
1244
|
-
}
|
|
1245
|
-
},
|
|
1246
|
-
_pagedRelationLinks: {
|
|
1247
|
-
type: "object",
|
|
1248
|
-
allOf: [
|
|
1249
|
-
{
|
|
1250
|
-
$ref: "#/components/schemas/_relationLinks"
|
|
1251
|
-
},
|
|
1252
|
-
{
|
|
1253
|
-
$ref: "#/components/schemas/_pagination"
|
|
1254
|
-
}
|
|
1255
|
-
]
|
|
1256
|
-
},
|
|
1257
|
-
_toOneRelationship: {
|
|
1258
|
-
type: "object",
|
|
1259
|
-
properties: {
|
|
1260
|
-
data: {
|
|
1261
|
-
oneOf: [
|
|
1262
|
-
{
|
|
1263
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1264
|
-
},
|
|
1265
|
-
{
|
|
1266
|
-
type: "null"
|
|
1267
|
-
}
|
|
1268
|
-
]
|
|
1269
|
-
}
|
|
1270
|
-
}
|
|
1271
|
-
},
|
|
1272
|
-
_toManyRelationship: {
|
|
1273
|
-
type: "object",
|
|
1274
|
-
properties: {
|
|
1275
|
-
data: {
|
|
1276
|
-
type: "array",
|
|
1277
|
-
items: {
|
|
1278
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
},
|
|
1283
|
-
_toOneRelationshipWithLinks: {
|
|
1284
|
-
type: "object",
|
|
1285
|
-
allOf: [
|
|
1286
|
-
{
|
|
1287
|
-
$ref: "#/components/schemas/_toOneRelationship"
|
|
1288
|
-
},
|
|
1289
|
-
{
|
|
1290
|
-
properties: {
|
|
1291
|
-
links: {
|
|
1292
|
-
$ref: "#/components/schemas/_relationLinks"
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
]
|
|
1297
|
-
},
|
|
1298
|
-
_toManyRelationshipWithLinks: {
|
|
1299
|
-
type: "object",
|
|
1300
|
-
allOf: [
|
|
1301
|
-
{
|
|
1302
|
-
$ref: "#/components/schemas/_toManyRelationship"
|
|
1303
|
-
},
|
|
1304
|
-
{
|
|
1305
|
-
properties: {
|
|
1306
|
-
links: {
|
|
1307
|
-
$ref: "#/components/schemas/_pagedRelationLinks"
|
|
1308
|
-
}
|
|
1309
|
-
}
|
|
1310
|
-
}
|
|
1311
|
-
]
|
|
1312
|
-
},
|
|
1313
|
-
_toManyRelationshipRequest: {
|
|
1314
|
-
type: "object",
|
|
1315
|
-
properties: {
|
|
1316
|
-
data: {
|
|
1317
|
-
type: "array",
|
|
1318
|
-
items: {
|
|
1319
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1320
|
-
}
|
|
1321
|
-
}
|
|
1322
|
-
},
|
|
1323
|
-
required: [
|
|
1324
|
-
"data"
|
|
1325
|
-
]
|
|
1326
|
-
},
|
|
1327
|
-
_toOneRelationshipRequest: {
|
|
1328
|
-
type: "object",
|
|
1329
|
-
properties: {
|
|
1330
|
-
data: {
|
|
1331
|
-
oneOf: [
|
|
1332
|
-
{
|
|
1333
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1334
|
-
},
|
|
1335
|
-
{
|
|
1336
|
-
type: "null"
|
|
1337
|
-
}
|
|
1338
|
-
]
|
|
1339
|
-
}
|
|
1340
|
-
},
|
|
1341
|
-
required: [
|
|
1342
|
-
"data"
|
|
1343
|
-
]
|
|
1344
|
-
},
|
|
1345
|
-
_toManyRelationshipResponse: {
|
|
1346
|
-
type: "object",
|
|
1347
|
-
properties: {
|
|
1348
|
-
data: {
|
|
1349
|
-
type: "array",
|
|
1350
|
-
items: {
|
|
1351
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1352
|
-
}
|
|
1353
|
-
},
|
|
1354
|
-
links: {
|
|
1355
|
-
$ref: "#/components/schemas/_pagedRelationLinks"
|
|
1356
|
-
},
|
|
1357
|
-
meta: {
|
|
1358
|
-
$ref: "#/components/schemas/_meta"
|
|
1359
|
-
}
|
|
1360
|
-
}
|
|
1361
|
-
},
|
|
1362
|
-
_toOneRelationshipResponse: {
|
|
1363
|
-
type: "object",
|
|
1364
|
-
properties: {
|
|
1365
|
-
data: {
|
|
1366
|
-
oneOf: [
|
|
1367
|
-
{
|
|
1368
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1369
|
-
},
|
|
1370
|
-
{
|
|
1371
|
-
type: "null"
|
|
1372
|
-
}
|
|
1373
|
-
]
|
|
1374
|
-
},
|
|
1375
|
-
links: {
|
|
1376
|
-
$ref: "#/components/schemas/_relationLinks"
|
|
1377
|
-
},
|
|
1378
|
-
meta: {
|
|
1379
|
-
$ref: "#/components/schemas/_meta"
|
|
1380
|
-
}
|
|
1381
|
-
}
|
|
1382
|
-
}
|
|
1383
|
-
};
|
|
1384
|
-
}
|
|
1385
|
-
buildEnumSchema(enumDef) {
|
|
1386
|
-
return {
|
|
1387
|
-
type: "string",
|
|
1388
|
-
enum: Object.values(enumDef.values)
|
|
1389
|
-
};
|
|
1390
|
-
}
|
|
1391
|
-
buildTypeDefSchema(typeDef) {
|
|
1392
|
-
const properties = {};
|
|
1393
|
-
const required = [];
|
|
1394
|
-
for (const [fieldName, fieldDef] of Object.entries(typeDef.fields)) {
|
|
1395
|
-
properties[fieldName] = this.fieldToSchema(fieldDef);
|
|
1396
|
-
if (!fieldDef.optional && !fieldDef.array) {
|
|
1397
|
-
required.push(fieldName);
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
const result = {
|
|
1401
|
-
type: "object",
|
|
1402
|
-
properties
|
|
1403
|
-
};
|
|
1404
|
-
if (required.length > 0) {
|
|
1405
|
-
result.required = required;
|
|
1406
|
-
}
|
|
1407
|
-
return result;
|
|
1408
|
-
}
|
|
1409
|
-
buildModelReadSchema(modelName, modelDef) {
|
|
1410
|
-
const attrProperties = {};
|
|
1411
|
-
const attrRequired = [];
|
|
1412
|
-
const relProperties = {};
|
|
1413
|
-
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
1414
|
-
if (fieldDef.omit) continue;
|
|
1415
|
-
if (isFieldOmitted(modelName, fieldName, this.queryOptions)) continue;
|
|
1416
|
-
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
1417
|
-
if (fieldDef.relation) {
|
|
1418
|
-
const relRef = fieldDef.array ? {
|
|
1419
|
-
$ref: "#/components/schemas/_toManyRelationshipWithLinks"
|
|
1420
|
-
} : {
|
|
1421
|
-
$ref: "#/components/schemas/_toOneRelationshipWithLinks"
|
|
1422
|
-
};
|
|
1423
|
-
relProperties[fieldName] = fieldDef.optional ? {
|
|
1424
|
-
oneOf: [
|
|
1425
|
-
{
|
|
1426
|
-
type: "null"
|
|
1427
|
-
},
|
|
1428
|
-
relRef
|
|
1429
|
-
]
|
|
1430
|
-
} : relRef;
|
|
1431
|
-
} else {
|
|
1432
|
-
const schema = this.fieldToSchema(fieldDef);
|
|
1433
|
-
const fieldDescription = getMetaDescription(fieldDef.attributes);
|
|
1434
|
-
if (fieldDescription && !("$ref" in schema)) {
|
|
1435
|
-
schema.description = fieldDescription;
|
|
1436
|
-
}
|
|
1437
|
-
attrProperties[fieldName] = schema;
|
|
1438
|
-
if (!fieldDef.optional && !fieldDef.array) {
|
|
1439
|
-
attrRequired.push(fieldName);
|
|
1440
|
-
}
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
const properties = {};
|
|
1444
|
-
if (Object.keys(attrProperties).length > 0) {
|
|
1445
|
-
const attrSchema = {
|
|
1446
|
-
type: "object",
|
|
1447
|
-
properties: attrProperties
|
|
1448
|
-
};
|
|
1449
|
-
if (attrRequired.length > 0) attrSchema.required = attrRequired;
|
|
1450
|
-
properties["attributes"] = attrSchema;
|
|
1451
|
-
}
|
|
1452
|
-
if (Object.keys(relProperties).length > 0) {
|
|
1453
|
-
properties["relationships"] = {
|
|
1454
|
-
type: "object",
|
|
1455
|
-
properties: relProperties
|
|
1456
|
-
};
|
|
1457
|
-
}
|
|
1458
|
-
const result = {
|
|
1459
|
-
type: "object",
|
|
1460
|
-
properties
|
|
1461
|
-
};
|
|
1462
|
-
const description = getMetaDescription(modelDef.attributes);
|
|
1463
|
-
if (description) {
|
|
1464
|
-
result.description = description;
|
|
1465
|
-
}
|
|
1466
|
-
return result;
|
|
1467
|
-
}
|
|
1468
|
-
buildCreateRequestSchema(_modelName, modelDef) {
|
|
1469
|
-
const idFieldNames = new Set(modelDef.idFields);
|
|
1470
|
-
const attributes = {};
|
|
1471
|
-
const attrRequired = [];
|
|
1472
|
-
const relationships = {};
|
|
1473
|
-
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
1474
|
-
if (fieldDef.updatedAt) continue;
|
|
1475
|
-
if (fieldDef.foreignKeyFor) continue;
|
|
1476
|
-
if (idFieldNames.has(fieldName) && fieldDef.default !== void 0) continue;
|
|
1477
|
-
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
1478
|
-
if (fieldDef.relation) {
|
|
1479
|
-
relationships[fieldName] = fieldDef.array ? {
|
|
1480
|
-
type: "object",
|
|
1481
|
-
properties: {
|
|
1482
|
-
data: {
|
|
1483
|
-
type: "array",
|
|
1484
|
-
items: {
|
|
1485
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1486
|
-
}
|
|
1487
|
-
}
|
|
1488
|
-
}
|
|
1489
|
-
} : {
|
|
1490
|
-
type: "object",
|
|
1491
|
-
properties: {
|
|
1492
|
-
data: {
|
|
1493
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1494
|
-
}
|
|
1495
|
-
}
|
|
1496
|
-
};
|
|
1497
|
-
} else {
|
|
1498
|
-
attributes[fieldName] = this.fieldToSchema(fieldDef);
|
|
1499
|
-
if (!fieldDef.optional && fieldDef.default === void 0 && !fieldDef.array) {
|
|
1500
|
-
attrRequired.push(fieldName);
|
|
1501
|
-
}
|
|
1502
|
-
}
|
|
1503
|
-
}
|
|
1504
|
-
const dataProperties = {
|
|
1505
|
-
type: {
|
|
1506
|
-
type: "string"
|
|
1507
|
-
}
|
|
1508
|
-
};
|
|
1509
|
-
if (Object.keys(attributes).length > 0) {
|
|
1510
|
-
const attrSchema = {
|
|
1511
|
-
type: "object",
|
|
1512
|
-
properties: attributes
|
|
1513
|
-
};
|
|
1514
|
-
if (attrRequired.length > 0) attrSchema.required = attrRequired;
|
|
1515
|
-
dataProperties["attributes"] = attrSchema;
|
|
1516
|
-
}
|
|
1517
|
-
if (Object.keys(relationships).length > 0) {
|
|
1518
|
-
dataProperties["relationships"] = {
|
|
1519
|
-
type: "object",
|
|
1520
|
-
properties: relationships
|
|
1521
|
-
};
|
|
1522
|
-
}
|
|
1523
|
-
return {
|
|
1524
|
-
type: "object",
|
|
1525
|
-
properties: {
|
|
1526
|
-
data: {
|
|
1527
|
-
type: "object",
|
|
1528
|
-
properties: dataProperties,
|
|
1529
|
-
required: [
|
|
1530
|
-
"type"
|
|
1531
|
-
]
|
|
1532
|
-
}
|
|
1533
|
-
},
|
|
1534
|
-
required: [
|
|
1535
|
-
"data"
|
|
1536
|
-
]
|
|
1537
|
-
};
|
|
1538
|
-
}
|
|
1539
|
-
buildUpdateRequestSchema(modelDef) {
|
|
1540
|
-
const attributes = {};
|
|
1541
|
-
const relationships = {};
|
|
1542
|
-
for (const [fieldName, fieldDef] of Object.entries(modelDef.fields)) {
|
|
1543
|
-
if (fieldDef.updatedAt) continue;
|
|
1544
|
-
if (fieldDef.foreignKeyFor) continue;
|
|
1545
|
-
if (fieldDef.relation && !isModelIncluded(fieldDef.type, this.queryOptions)) continue;
|
|
1546
|
-
if (fieldDef.relation) {
|
|
1547
|
-
relationships[fieldName] = fieldDef.array ? {
|
|
1548
|
-
type: "object",
|
|
1549
|
-
properties: {
|
|
1550
|
-
data: {
|
|
1551
|
-
type: "array",
|
|
1552
|
-
items: {
|
|
1553
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
}
|
|
1557
|
-
} : {
|
|
1558
|
-
type: "object",
|
|
1559
|
-
properties: {
|
|
1560
|
-
data: {
|
|
1561
|
-
$ref: "#/components/schemas/_resourceIdentifier"
|
|
1562
|
-
}
|
|
1563
|
-
}
|
|
1564
|
-
};
|
|
1565
|
-
} else {
|
|
1566
|
-
attributes[fieldName] = this.fieldToSchema(fieldDef);
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
const dataProperties = {
|
|
1570
|
-
type: {
|
|
1571
|
-
type: "string"
|
|
1572
|
-
},
|
|
1573
|
-
id: {
|
|
1574
|
-
type: "string"
|
|
1575
|
-
}
|
|
1576
|
-
};
|
|
1577
|
-
if (Object.keys(attributes).length > 0) {
|
|
1578
|
-
dataProperties["attributes"] = {
|
|
1579
|
-
type: "object",
|
|
1580
|
-
properties: attributes
|
|
1581
|
-
};
|
|
1582
|
-
}
|
|
1583
|
-
if (Object.keys(relationships).length > 0) {
|
|
1584
|
-
dataProperties["relationships"] = {
|
|
1585
|
-
type: "object",
|
|
1586
|
-
properties: relationships
|
|
1587
|
-
};
|
|
1588
|
-
}
|
|
1589
|
-
return {
|
|
1590
|
-
type: "object",
|
|
1591
|
-
properties: {
|
|
1592
|
-
data: {
|
|
1593
|
-
type: "object",
|
|
1594
|
-
properties: dataProperties,
|
|
1595
|
-
required: [
|
|
1596
|
-
"type",
|
|
1597
|
-
"id"
|
|
1598
|
-
]
|
|
1599
|
-
}
|
|
1600
|
-
},
|
|
1601
|
-
required: [
|
|
1602
|
-
"data"
|
|
1603
|
-
]
|
|
1604
|
-
};
|
|
1605
|
-
}
|
|
1606
|
-
buildModelResponseSchema(modelName) {
|
|
1607
|
-
return {
|
|
1608
|
-
type: "object",
|
|
1609
|
-
properties: {
|
|
1610
|
-
jsonapi: {
|
|
1611
|
-
$ref: "#/components/schemas/_jsonapi"
|
|
1612
|
-
},
|
|
1613
|
-
data: {
|
|
1614
|
-
allOf: [
|
|
1615
|
-
{
|
|
1616
|
-
$ref: `#/components/schemas/${modelName}`
|
|
1617
|
-
},
|
|
1618
|
-
{
|
|
1619
|
-
$ref: "#/components/schemas/_resource"
|
|
1620
|
-
}
|
|
1621
|
-
]
|
|
1622
|
-
},
|
|
1623
|
-
meta: {
|
|
1624
|
-
$ref: "#/components/schemas/_meta"
|
|
1625
|
-
}
|
|
1626
|
-
}
|
|
1627
|
-
};
|
|
1628
|
-
}
|
|
1629
|
-
buildModelListResponseSchema(modelName) {
|
|
1630
|
-
return {
|
|
1631
|
-
type: "object",
|
|
1632
|
-
properties: {
|
|
1633
|
-
jsonapi: {
|
|
1634
|
-
$ref: "#/components/schemas/_jsonapi"
|
|
1635
|
-
},
|
|
1636
|
-
data: {
|
|
1637
|
-
type: "array",
|
|
1638
|
-
items: {
|
|
1639
|
-
allOf: [
|
|
1640
|
-
{
|
|
1641
|
-
$ref: `#/components/schemas/${modelName}`
|
|
1642
|
-
},
|
|
1643
|
-
{
|
|
1644
|
-
$ref: "#/components/schemas/_resource"
|
|
1645
|
-
}
|
|
1646
|
-
]
|
|
1647
|
-
}
|
|
1648
|
-
},
|
|
1649
|
-
links: {
|
|
1650
|
-
allOf: [
|
|
1651
|
-
{
|
|
1652
|
-
$ref: "#/components/schemas/_pagination"
|
|
1653
|
-
},
|
|
1654
|
-
{
|
|
1655
|
-
$ref: "#/components/schemas/_links"
|
|
1656
|
-
}
|
|
1657
|
-
]
|
|
1658
|
-
},
|
|
1659
|
-
meta: {
|
|
1660
|
-
$ref: "#/components/schemas/_meta"
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
};
|
|
1664
|
-
}
|
|
1665
|
-
generateSharedParams() {
|
|
1666
|
-
return {
|
|
1667
|
-
id: {
|
|
1668
|
-
name: "id",
|
|
1669
|
-
in: "path",
|
|
1670
|
-
required: true,
|
|
1671
|
-
schema: {
|
|
1672
|
-
type: "string"
|
|
1673
|
-
},
|
|
1674
|
-
description: "Resource ID"
|
|
1675
|
-
},
|
|
1676
|
-
include: {
|
|
1677
|
-
name: "include",
|
|
1678
|
-
in: "query",
|
|
1679
|
-
schema: {
|
|
1680
|
-
type: "string"
|
|
1681
|
-
},
|
|
1682
|
-
description: "Comma-separated list of relationships to include"
|
|
1683
|
-
},
|
|
1684
|
-
sort: {
|
|
1685
|
-
name: "sort",
|
|
1686
|
-
in: "query",
|
|
1687
|
-
schema: {
|
|
1688
|
-
type: "string"
|
|
1689
|
-
},
|
|
1690
|
-
description: "Comma-separated list of fields to sort by. Prefix with - for descending"
|
|
1691
|
-
},
|
|
1692
|
-
pageOffset: {
|
|
1693
|
-
name: "page[offset]",
|
|
1694
|
-
in: "query",
|
|
1695
|
-
schema: {
|
|
1696
|
-
type: "integer",
|
|
1697
|
-
minimum: 0
|
|
1698
|
-
},
|
|
1699
|
-
description: "Page offset"
|
|
1700
|
-
},
|
|
1701
|
-
pageLimit: {
|
|
1702
|
-
name: "page[limit]",
|
|
1703
|
-
in: "query",
|
|
1704
|
-
schema: {
|
|
1705
|
-
type: "integer",
|
|
1706
|
-
minimum: 1
|
|
1707
|
-
},
|
|
1708
|
-
description: "Page limit"
|
|
1709
|
-
}
|
|
1710
|
-
};
|
|
1711
|
-
}
|
|
1712
|
-
fieldToSchema(fieldDef) {
|
|
1713
|
-
const baseSchema = this.typeToSchema(fieldDef.type);
|
|
1714
|
-
if (fieldDef.array) {
|
|
1715
|
-
return {
|
|
1716
|
-
type: "array",
|
|
1717
|
-
items: baseSchema
|
|
1718
|
-
};
|
|
1719
|
-
}
|
|
1720
|
-
if (fieldDef.optional) {
|
|
1721
|
-
return {
|
|
1722
|
-
oneOf: [
|
|
1723
|
-
baseSchema,
|
|
1724
|
-
{
|
|
1725
|
-
type: "null"
|
|
1726
|
-
}
|
|
1727
|
-
]
|
|
1728
|
-
};
|
|
1729
|
-
}
|
|
1730
|
-
return baseSchema;
|
|
1731
|
-
}
|
|
1732
|
-
typeToSchema(type) {
|
|
1733
|
-
switch (type) {
|
|
1734
|
-
case "String":
|
|
1735
|
-
return {
|
|
1736
|
-
type: "string"
|
|
1737
|
-
};
|
|
1738
|
-
case "Int":
|
|
1739
|
-
case "BigInt":
|
|
1740
|
-
return {
|
|
1741
|
-
type: "integer"
|
|
1742
|
-
};
|
|
1743
|
-
case "Float":
|
|
1744
|
-
return {
|
|
1745
|
-
type: "number"
|
|
1746
|
-
};
|
|
1747
|
-
case "Decimal":
|
|
1748
|
-
return {
|
|
1749
|
-
oneOf: [
|
|
1750
|
-
{
|
|
1751
|
-
type: "number"
|
|
1752
|
-
},
|
|
1753
|
-
{
|
|
1754
|
-
type: "string"
|
|
1755
|
-
}
|
|
1756
|
-
]
|
|
1757
|
-
};
|
|
1758
|
-
case "Boolean":
|
|
1759
|
-
return {
|
|
1760
|
-
type: "boolean"
|
|
1761
|
-
};
|
|
1762
|
-
case "DateTime":
|
|
1763
|
-
return {
|
|
1764
|
-
type: "string",
|
|
1765
|
-
format: "date-time"
|
|
1766
|
-
};
|
|
1767
|
-
case "Bytes":
|
|
1768
|
-
return {
|
|
1769
|
-
type: "string",
|
|
1770
|
-
format: "byte"
|
|
1771
|
-
};
|
|
1772
|
-
case "Json":
|
|
1773
|
-
case "Unsupported":
|
|
1774
|
-
return {};
|
|
1775
|
-
default:
|
|
1776
|
-
return {
|
|
1777
|
-
$ref: `#/components/schemas/${type}`
|
|
1778
|
-
};
|
|
1779
|
-
}
|
|
1780
|
-
}
|
|
1781
|
-
getIdFields(modelDef) {
|
|
1782
|
-
return modelDef.idFields.map((name) => modelDef.fields[name]).filter((f) => f !== void 0);
|
|
1783
|
-
}
|
|
1784
|
-
/**
|
|
1785
|
-
* Checks if an operation on a model may be denied by access policies.
|
|
1786
|
-
* Returns true when `respectAccessPolicies` is enabled and the model's
|
|
1787
|
-
* policies for the given operation are NOT a constant allow (i.e., not
|
|
1788
|
-
* simply `@@allow('...', true)` with no `@@deny` rules).
|
|
1789
|
-
*/
|
|
1790
|
-
mayDenyAccess(modelDef, operation) {
|
|
1791
|
-
if (!this.specOptions?.respectAccessPolicies) return false;
|
|
1792
|
-
const policyAttrs = (modelDef.attributes ?? []).filter((attr) => attr.name === "@@allow" || attr.name === "@@deny");
|
|
1793
|
-
if (policyAttrs.length === 0) return true;
|
|
1794
|
-
const getArgByName = /* @__PURE__ */ __name((args, name) => args?.find((a) => a.name === name)?.value, "getArgByName");
|
|
1795
|
-
const matchesOperation = /* @__PURE__ */ __name((args) => {
|
|
1796
|
-
const val = getArgByName(args, "operation");
|
|
1797
|
-
if (!val || val.kind !== "literal" || typeof val.value !== "string") return false;
|
|
1798
|
-
const ops = val.value.split(",").map((s) => s.trim());
|
|
1799
|
-
return ops.includes(operation) || ops.includes("all");
|
|
1800
|
-
}, "matchesOperation");
|
|
1801
|
-
const hasEffectiveDeny = policyAttrs.some((attr) => {
|
|
1802
|
-
if (attr.name !== "@@deny" || !matchesOperation(attr.args)) return false;
|
|
1803
|
-
const condition = getArgByName(attr.args, "condition");
|
|
1804
|
-
return !(condition?.kind === "literal" && condition.value === false);
|
|
1805
|
-
});
|
|
1806
|
-
if (hasEffectiveDeny) return true;
|
|
1807
|
-
const relevantAllow = policyAttrs.filter((attr) => attr.name === "@@allow" && matchesOperation(attr.args));
|
|
1808
|
-
const hasConstantAllow = relevantAllow.some((attr) => {
|
|
1809
|
-
const condition = getArgByName(attr.args, "condition");
|
|
1810
|
-
return condition?.kind === "literal" && condition.value === true;
|
|
1811
|
-
});
|
|
1812
|
-
return !hasConstantAllow;
|
|
1813
|
-
}
|
|
1814
|
-
};
|
|
1815
|
-
|
|
1816
|
-
// src/api/rest/index.ts
|
|
1817
|
-
var InvalidValueError = class InvalidValueError2 extends Error {
|
|
1818
|
-
static {
|
|
1819
|
-
__name(this, "InvalidValueError");
|
|
1820
|
-
}
|
|
1821
|
-
constructor(message) {
|
|
1822
|
-
super(message);
|
|
1823
|
-
}
|
|
1824
|
-
};
|
|
1825
|
-
var DEFAULT_PAGE_SIZE = 100;
|
|
1826
|
-
var FilterOperations = [
|
|
1827
|
-
"lt",
|
|
1828
|
-
"lte",
|
|
1829
|
-
"gt",
|
|
1830
|
-
"gte",
|
|
1831
|
-
"between",
|
|
1832
|
-
"contains",
|
|
1833
|
-
"icontains",
|
|
1834
|
-
"search",
|
|
1835
|
-
"startsWith",
|
|
1836
|
-
"endsWith",
|
|
1837
|
-
"has",
|
|
1838
|
-
"hasEvery",
|
|
1839
|
-
"hasSome",
|
|
1840
|
-
"isEmpty"
|
|
1841
|
-
];
|
|
1842
|
-
var DEFAULT_ID_DIVIDER = "_";
|
|
1843
|
-
registerCustomSerializers();
|
|
1844
|
-
var RestApiHandler = class {
|
|
1845
|
-
static {
|
|
1846
|
-
__name(this, "RestApiHandler");
|
|
1847
|
-
}
|
|
1848
|
-
options;
|
|
1849
|
-
// resource serializers
|
|
1850
|
-
serializers = /* @__PURE__ */ new Map();
|
|
1851
|
-
// error responses
|
|
1852
|
-
errors = {
|
|
1853
|
-
unsupportedModel: {
|
|
1854
|
-
status: 404,
|
|
1855
|
-
title: "Unsupported model type",
|
|
1856
|
-
detail: "The model type is not supported"
|
|
1857
|
-
},
|
|
1858
|
-
unsupportedRelationship: {
|
|
1859
|
-
status: 400,
|
|
1860
|
-
title: "Unsupported relationship",
|
|
1861
|
-
detail: "The relationship is not supported"
|
|
1862
|
-
},
|
|
1863
|
-
invalidPath: {
|
|
1864
|
-
status: 400,
|
|
1865
|
-
title: "The request path is invalid"
|
|
1866
|
-
},
|
|
1867
|
-
invalidVerb: {
|
|
1868
|
-
status: 400,
|
|
1869
|
-
title: "The HTTP verb is not supported"
|
|
1870
|
-
},
|
|
1871
|
-
notFound: {
|
|
1872
|
-
status: 404,
|
|
1873
|
-
title: "Resource not found"
|
|
1874
|
-
},
|
|
1875
|
-
noId: {
|
|
1876
|
-
status: 400,
|
|
1877
|
-
title: "Model without an ID field is not supported"
|
|
1878
|
-
},
|
|
1879
|
-
invalidId: {
|
|
1880
|
-
status: 400,
|
|
1881
|
-
title: "Resource ID is invalid"
|
|
1882
|
-
},
|
|
1883
|
-
invalidPayload: {
|
|
1884
|
-
status: 400,
|
|
1885
|
-
title: "Invalid payload"
|
|
1886
|
-
},
|
|
1887
|
-
invalidRelationData: {
|
|
1888
|
-
status: 400,
|
|
1889
|
-
title: "Invalid relation data",
|
|
1890
|
-
detail: "Invalid relationship data"
|
|
1891
|
-
},
|
|
1892
|
-
invalidRelation: {
|
|
1893
|
-
status: 400,
|
|
1894
|
-
title: "Invalid relation",
|
|
1895
|
-
detail: "Invalid relationship"
|
|
1896
|
-
},
|
|
1897
|
-
invalidFilter: {
|
|
1898
|
-
status: 400,
|
|
1899
|
-
title: "Invalid filter"
|
|
1900
|
-
},
|
|
1901
|
-
invalidSort: {
|
|
1902
|
-
status: 400,
|
|
1903
|
-
title: "Invalid sort"
|
|
1904
|
-
},
|
|
1905
|
-
invalidValue: {
|
|
1906
|
-
status: 400,
|
|
1907
|
-
title: "Invalid value for type"
|
|
1908
|
-
},
|
|
1909
|
-
duplicatedFieldsParameter: {
|
|
1910
|
-
status: 400,
|
|
1911
|
-
title: "Fields Parameter Duplicated"
|
|
1912
|
-
},
|
|
1913
|
-
forbidden: {
|
|
1914
|
-
status: 403,
|
|
1915
|
-
title: "Operation is forbidden"
|
|
1916
|
-
},
|
|
1917
|
-
validationError: {
|
|
1918
|
-
status: 422,
|
|
1919
|
-
title: "Operation is unprocessable due to validation errors"
|
|
1920
|
-
},
|
|
1921
|
-
queryError: {
|
|
1922
|
-
status: 400,
|
|
1923
|
-
title: "Error occurred while executing the query"
|
|
1924
|
-
},
|
|
1925
|
-
unknownError: {
|
|
1926
|
-
status: 500,
|
|
1927
|
-
title: "Unknown error"
|
|
1928
|
-
}
|
|
1929
|
-
};
|
|
1930
|
-
filterParamPattern = new RegExp(/^filter(?<match>(\[[^[\]]+\])+)$/);
|
|
1931
|
-
// zod schema for payload of creating and updating a resource
|
|
1932
|
-
createUpdatePayloadSchema = z2.object({
|
|
1933
|
-
data: z2.object({
|
|
1934
|
-
type: z2.string(),
|
|
1935
|
-
attributes: z2.object({}).passthrough().optional(),
|
|
1936
|
-
relationships: z2.record(z2.string(), z2.object({
|
|
1937
|
-
data: z2.union([
|
|
1938
|
-
z2.object({
|
|
1939
|
-
type: z2.string(),
|
|
1940
|
-
id: z2.union([
|
|
1941
|
-
z2.string(),
|
|
1942
|
-
z2.number()
|
|
1943
|
-
])
|
|
1944
|
-
}),
|
|
1945
|
-
z2.array(z2.object({
|
|
1946
|
-
type: z2.string(),
|
|
1947
|
-
id: z2.union([
|
|
1948
|
-
z2.string(),
|
|
1949
|
-
z2.number()
|
|
1950
|
-
])
|
|
1951
|
-
}))
|
|
1952
|
-
])
|
|
1953
|
-
})).optional()
|
|
1954
|
-
}),
|
|
1955
|
-
meta: z2.object({}).passthrough().optional()
|
|
1956
|
-
}).strict();
|
|
1957
|
-
// zod schema for updating a single relationship
|
|
1958
|
-
updateSingleRelationSchema = z2.object({
|
|
1959
|
-
data: z2.object({
|
|
1960
|
-
type: z2.string(),
|
|
1961
|
-
id: z2.union([
|
|
1962
|
-
z2.string(),
|
|
1963
|
-
z2.number()
|
|
1964
|
-
])
|
|
1965
|
-
}).nullable()
|
|
1966
|
-
});
|
|
1967
|
-
// zod schema for updating collection relationship
|
|
1968
|
-
updateCollectionRelationSchema = z2.object({
|
|
1969
|
-
data: z2.array(z2.object({
|
|
1970
|
-
type: z2.string(),
|
|
1971
|
-
id: z2.union([
|
|
1972
|
-
z2.string(),
|
|
1973
|
-
z2.number()
|
|
1974
|
-
])
|
|
1975
|
-
}))
|
|
1976
|
-
});
|
|
1977
|
-
upsertMetaSchema = z2.object({
|
|
1978
|
-
meta: z2.object({
|
|
1979
|
-
operation: z2.literal("upsert"),
|
|
1980
|
-
matchFields: z2.array(z2.string()).min(1)
|
|
1981
|
-
})
|
|
1982
|
-
});
|
|
1983
|
-
// all known types and their metadata
|
|
1984
|
-
typeMap = {};
|
|
1985
|
-
// divider used to separate compound ID fields
|
|
1986
|
-
idDivider;
|
|
1987
|
-
urlPatternMap;
|
|
1988
|
-
modelNameMapping;
|
|
1989
|
-
reverseModelNameMapping;
|
|
1990
|
-
externalIdMapping;
|
|
1991
|
-
nestedRoutes;
|
|
1992
|
-
constructor(options) {
|
|
1993
|
-
this.options = options;
|
|
1994
|
-
this.validateOptions(options);
|
|
1995
|
-
this.idDivider = options.idDivider ?? DEFAULT_ID_DIVIDER;
|
|
1996
|
-
const segmentCharset = options.urlSegmentCharset ?? "a-zA-Z0-9-_~ %";
|
|
1997
|
-
this.modelNameMapping = options.modelNameMapping ?? {};
|
|
1998
|
-
this.modelNameMapping = Object.fromEntries(Object.entries(this.modelNameMapping).map(([k, v]) => [
|
|
1999
|
-
lowerCaseFirst3(k),
|
|
2000
|
-
v
|
|
2001
|
-
]));
|
|
2002
|
-
this.reverseModelNameMapping = Object.fromEntries(Object.entries(this.modelNameMapping).map(([k, v]) => [
|
|
2003
|
-
v,
|
|
2004
|
-
k
|
|
2005
|
-
]));
|
|
2006
|
-
this.externalIdMapping = options.externalIdMapping ?? {};
|
|
2007
|
-
this.externalIdMapping = Object.fromEntries(Object.entries(this.externalIdMapping).map(([k, v]) => [
|
|
2008
|
-
lowerCaseFirst3(k),
|
|
2009
|
-
v
|
|
2010
|
-
]));
|
|
2011
|
-
this.nestedRoutes = options.nestedRoutes ?? false;
|
|
2012
|
-
this.urlPatternMap = this.buildUrlPatternMap(segmentCharset);
|
|
2013
|
-
this.buildTypeMap();
|
|
2014
|
-
this.buildSerializers();
|
|
2015
|
-
}
|
|
2016
|
-
validateOptions(options) {
|
|
2017
|
-
const schema = z2.strictObject({
|
|
2018
|
-
schema: z2.object(),
|
|
2019
|
-
log: loggerSchema.optional(),
|
|
2020
|
-
endpoint: z2.string().min(1),
|
|
2021
|
-
pageSize: z2.union([
|
|
2022
|
-
z2.number().int().positive(),
|
|
2023
|
-
z2.literal(Infinity)
|
|
2024
|
-
]).optional(),
|
|
2025
|
-
idDivider: z2.string().min(1).optional(),
|
|
2026
|
-
urlSegmentCharset: z2.string().min(1).optional(),
|
|
2027
|
-
modelNameMapping: z2.record(z2.string(), z2.string()).optional(),
|
|
2028
|
-
externalIdMapping: z2.record(z2.string(), z2.string()).optional(),
|
|
2029
|
-
queryOptions: queryOptionsSchema.optional(),
|
|
2030
|
-
nestedRoutes: z2.boolean().optional()
|
|
2031
|
-
});
|
|
2032
|
-
const parseResult = schema.safeParse(options);
|
|
2033
|
-
if (!parseResult.success) {
|
|
2034
|
-
throw new Error(`Invalid options: ${fromError(parseResult.error)}`);
|
|
2035
|
-
}
|
|
2036
|
-
}
|
|
2037
|
-
get schema() {
|
|
2038
|
-
return this.options.schema;
|
|
2039
|
-
}
|
|
2040
|
-
get log() {
|
|
2041
|
-
return this.options.log;
|
|
2042
|
-
}
|
|
2043
|
-
buildUrlPatternMap(urlSegmentNameCharset) {
|
|
2044
|
-
const options = {
|
|
2045
|
-
segmentValueCharset: urlSegmentNameCharset
|
|
2046
|
-
};
|
|
2047
|
-
const buildPath = /* @__PURE__ */ __name((segments) => {
|
|
2048
|
-
return "/" + segments.join("/");
|
|
2049
|
-
}, "buildPath");
|
|
2050
|
-
return {
|
|
2051
|
-
["single"]: new UrlPattern(buildPath([
|
|
2052
|
-
":type",
|
|
2053
|
-
":id"
|
|
2054
|
-
]), options),
|
|
2055
|
-
["nestedSingle"]: new UrlPattern(buildPath([
|
|
2056
|
-
":type",
|
|
2057
|
-
":id",
|
|
2058
|
-
":relationship",
|
|
2059
|
-
":childId"
|
|
2060
|
-
]), options),
|
|
2061
|
-
["fetchRelationship"]: new UrlPattern(buildPath([
|
|
2062
|
-
":type",
|
|
2063
|
-
":id",
|
|
2064
|
-
":relationship"
|
|
2065
|
-
]), options),
|
|
2066
|
-
["relationship"]: new UrlPattern(buildPath([
|
|
2067
|
-
":type",
|
|
2068
|
-
":id",
|
|
2069
|
-
"relationships",
|
|
2070
|
-
":relationship"
|
|
2071
|
-
]), options),
|
|
2072
|
-
["collection"]: new UrlPattern(buildPath([
|
|
2073
|
-
":type"
|
|
2074
|
-
]), options)
|
|
2075
|
-
};
|
|
2076
|
-
}
|
|
2077
|
-
mapModelName(modelName) {
|
|
2078
|
-
return this.modelNameMapping[modelName] ?? modelName;
|
|
2079
|
-
}
|
|
2080
|
-
/**
|
|
2081
|
-
* Resolves child model type and reverse relation from a parent relation name.
|
|
2082
|
-
* e.g. given parentType='user', parentRelation='posts', returns { childType:'post', reverseRelation:'author' }
|
|
2083
|
-
*/
|
|
2084
|
-
resolveNestedRelation(parentType, parentRelation) {
|
|
2085
|
-
const parentInfo = this.getModelInfo(parentType);
|
|
2086
|
-
if (!parentInfo) return void 0;
|
|
2087
|
-
const field = this.schema.models[parentInfo.name]?.fields[parentRelation];
|
|
2088
|
-
if (!field?.relation) return void 0;
|
|
2089
|
-
const reverseRelation = field.relation.opposite;
|
|
2090
|
-
if (!reverseRelation) return void 0;
|
|
2091
|
-
return {
|
|
2092
|
-
childType: lowerCaseFirst3(field.type),
|
|
2093
|
-
reverseRelation,
|
|
2094
|
-
isCollection: !!field.array
|
|
2095
|
-
};
|
|
2096
|
-
}
|
|
2097
|
-
mergeFilters(left, right) {
|
|
2098
|
-
if (!left) {
|
|
2099
|
-
return right;
|
|
2100
|
-
}
|
|
2101
|
-
if (!right) {
|
|
2102
|
-
return left;
|
|
2103
|
-
}
|
|
2104
|
-
return {
|
|
2105
|
-
AND: [
|
|
2106
|
-
left,
|
|
2107
|
-
right
|
|
2108
|
-
]
|
|
2109
|
-
};
|
|
2110
|
-
}
|
|
2111
|
-
/**
|
|
2112
|
-
* Builds a WHERE filter for the child model that constrains results to those belonging to the given parent.
|
|
2113
|
-
* @param parentType lowercased parent model name
|
|
2114
|
-
* @param parentId parent resource ID string
|
|
2115
|
-
* @param parentRelation relation field name on the parent model (e.g. 'posts')
|
|
2116
|
-
*/
|
|
2117
|
-
buildNestedParentFilter(parentType, parentId, parentRelation) {
|
|
2118
|
-
const parentInfo = this.getModelInfo(parentType);
|
|
2119
|
-
if (!parentInfo) {
|
|
2120
|
-
return {
|
|
2121
|
-
filter: void 0,
|
|
2122
|
-
error: this.makeUnsupportedModelError(parentType)
|
|
2123
|
-
};
|
|
2124
|
-
}
|
|
2125
|
-
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
2126
|
-
if (!resolved) {
|
|
2127
|
-
return {
|
|
2128
|
-
filter: void 0,
|
|
2129
|
-
error: this.makeError("invalidPath", `invalid nested route: cannot resolve relation "${parentType}.${parentRelation}"`)
|
|
2130
|
-
};
|
|
2131
|
-
}
|
|
2132
|
-
const { reverseRelation } = resolved;
|
|
2133
|
-
const childInfo = this.getModelInfo(resolved.childType);
|
|
2134
|
-
if (!childInfo) {
|
|
2135
|
-
return {
|
|
2136
|
-
filter: void 0,
|
|
2137
|
-
error: this.makeUnsupportedModelError(resolved.childType)
|
|
2138
|
-
};
|
|
2139
|
-
}
|
|
2140
|
-
const reverseRelInfo = childInfo.relationships[reverseRelation];
|
|
2141
|
-
const relationFilter = reverseRelInfo?.isCollection ? {
|
|
2142
|
-
[reverseRelation]: {
|
|
2143
|
-
some: this.makeIdFilter(parentInfo.idFields, parentId, false)
|
|
2144
|
-
}
|
|
2145
|
-
} : {
|
|
2146
|
-
[reverseRelation]: {
|
|
2147
|
-
is: this.makeIdFilter(parentInfo.idFields, parentId, false)
|
|
2148
|
-
}
|
|
2149
|
-
};
|
|
2150
|
-
return {
|
|
2151
|
-
filter: relationFilter,
|
|
2152
|
-
error: void 0
|
|
2153
|
-
};
|
|
2154
|
-
}
|
|
2155
|
-
matchUrlPattern(path, routeType) {
|
|
2156
|
-
const pattern = this.urlPatternMap[routeType];
|
|
2157
|
-
if (!pattern) {
|
|
2158
|
-
throw new InvalidValueError(`Unknown route type: ${routeType}`);
|
|
2159
|
-
}
|
|
2160
|
-
const match4 = pattern.match(path);
|
|
2161
|
-
if (!match4) {
|
|
2162
|
-
return;
|
|
2163
|
-
}
|
|
2164
|
-
if (match4.type in this.modelNameMapping) {
|
|
2165
|
-
throw new InvalidValueError(`use the mapped model name: ${this.modelNameMapping[match4.type]} and not ${match4.type}`);
|
|
2166
|
-
}
|
|
2167
|
-
if (match4.type in this.reverseModelNameMapping) {
|
|
2168
|
-
match4.type = this.reverseModelNameMapping[match4.type];
|
|
2169
|
-
}
|
|
2170
|
-
return match4;
|
|
2171
|
-
}
|
|
2172
|
-
async handleRequest({ client, method, path, query, requestBody }) {
|
|
2173
|
-
method = method.toUpperCase();
|
|
2174
|
-
if (!path.startsWith("/")) {
|
|
2175
|
-
path = "/" + path;
|
|
2176
|
-
}
|
|
2177
|
-
try {
|
|
2178
|
-
if (path.startsWith("/$procs/")) {
|
|
2179
|
-
const proc = path.split("/")[2];
|
|
2180
|
-
return await this.processProcedureRequest({
|
|
2181
|
-
client,
|
|
2182
|
-
method,
|
|
2183
|
-
proc,
|
|
2184
|
-
query,
|
|
2185
|
-
requestBody
|
|
2186
|
-
});
|
|
2187
|
-
}
|
|
2188
|
-
switch (method) {
|
|
2189
|
-
case "GET": {
|
|
2190
|
-
let match4 = this.matchUrlPattern(path, "single");
|
|
2191
|
-
if (match4) {
|
|
2192
|
-
return await this.processSingleRead(client, match4.type, match4.id, query);
|
|
2193
|
-
}
|
|
2194
|
-
match4 = this.matchUrlPattern(path, "fetchRelationship");
|
|
2195
|
-
if (match4) {
|
|
2196
|
-
return await this.processFetchRelated(client, match4.type, match4.id, match4.relationship, query);
|
|
2197
|
-
}
|
|
2198
|
-
match4 = this.matchUrlPattern(path, "relationship");
|
|
2199
|
-
if (match4) {
|
|
2200
|
-
return await this.processReadRelationship(client, match4.type, match4.id, match4.relationship, query);
|
|
2201
|
-
}
|
|
2202
|
-
match4 = this.matchUrlPattern(path, "nestedSingle");
|
|
2203
|
-
if (match4 && this.nestedRoutes && this.resolveNestedRelation(match4.type, match4.relationship)?.isCollection) {
|
|
2204
|
-
return await this.processNestedSingleRead(client, match4.type, match4.id, match4.relationship, match4.childId, query);
|
|
2205
|
-
}
|
|
2206
|
-
match4 = this.matchUrlPattern(path, "collection");
|
|
2207
|
-
if (match4) {
|
|
2208
|
-
return await this.processCollectionRead(client, match4.type, query);
|
|
2209
|
-
}
|
|
2210
|
-
return this.makeError("invalidPath");
|
|
2211
|
-
}
|
|
2212
|
-
case "POST": {
|
|
2213
|
-
if (!requestBody) {
|
|
2214
|
-
return this.makeError("invalidPayload");
|
|
2215
|
-
}
|
|
2216
|
-
const nestedMatch = this.matchUrlPattern(path, "fetchRelationship");
|
|
2217
|
-
if (nestedMatch && this.nestedRoutes && this.resolveNestedRelation(nestedMatch.type, nestedMatch.relationship)?.isCollection) {
|
|
2218
|
-
return await this.processNestedCreate(client, nestedMatch.type, nestedMatch.id, nestedMatch.relationship, query, requestBody);
|
|
2219
|
-
}
|
|
2220
|
-
let match4 = this.matchUrlPattern(path, "collection");
|
|
2221
|
-
if (match4) {
|
|
2222
|
-
const body = requestBody;
|
|
2223
|
-
const upsertMeta = this.upsertMetaSchema.safeParse(body);
|
|
2224
|
-
if (upsertMeta.success) {
|
|
2225
|
-
return await this.processUpsert(client, match4.type, query, requestBody);
|
|
2226
|
-
} else {
|
|
2227
|
-
return await this.processCreate(client, match4.type, query, requestBody);
|
|
2228
|
-
}
|
|
2229
|
-
}
|
|
2230
|
-
match4 = this.matchUrlPattern(path, "relationship");
|
|
2231
|
-
if (match4) {
|
|
2232
|
-
return await this.processRelationshipCRUD(client, "create", match4.type, match4.id, match4.relationship, query, requestBody);
|
|
2233
|
-
}
|
|
2234
|
-
return this.makeError("invalidPath");
|
|
2235
|
-
}
|
|
2236
|
-
// TODO: PUT for full update
|
|
2237
|
-
case "PUT":
|
|
2238
|
-
case "PATCH": {
|
|
2239
|
-
if (!requestBody) {
|
|
2240
|
-
return this.makeError("invalidPayload");
|
|
2241
|
-
}
|
|
2242
|
-
let match4 = this.matchUrlPattern(path, "relationship");
|
|
2243
|
-
if (match4) {
|
|
2244
|
-
return await this.processRelationshipCRUD(client, "update", match4.type, match4.id, match4.relationship, query, requestBody);
|
|
2245
|
-
}
|
|
2246
|
-
const nestedToOnePatchMatch = this.matchUrlPattern(path, "fetchRelationship");
|
|
2247
|
-
if (nestedToOnePatchMatch && this.nestedRoutes && this.resolveNestedRelation(nestedToOnePatchMatch.type, nestedToOnePatchMatch.relationship) && !this.resolveNestedRelation(nestedToOnePatchMatch.type, nestedToOnePatchMatch.relationship)?.isCollection) {
|
|
2248
|
-
return await this.processNestedUpdate(client, nestedToOnePatchMatch.type, nestedToOnePatchMatch.id, nestedToOnePatchMatch.relationship, void 0, query, requestBody);
|
|
2249
|
-
}
|
|
2250
|
-
const nestedPatchMatch = this.matchUrlPattern(path, "nestedSingle");
|
|
2251
|
-
if (nestedPatchMatch && this.nestedRoutes && this.resolveNestedRelation(nestedPatchMatch.type, nestedPatchMatch.relationship)?.isCollection) {
|
|
2252
|
-
return await this.processNestedUpdate(client, nestedPatchMatch.type, nestedPatchMatch.id, nestedPatchMatch.relationship, nestedPatchMatch.childId, query, requestBody);
|
|
2253
|
-
}
|
|
2254
|
-
match4 = this.matchUrlPattern(path, "single");
|
|
2255
|
-
if (match4) {
|
|
2256
|
-
return await this.processUpdate(client, match4.type, match4.id, query, requestBody);
|
|
2257
|
-
}
|
|
2258
|
-
return this.makeError("invalidPath");
|
|
2259
|
-
}
|
|
2260
|
-
case "DELETE": {
|
|
2261
|
-
let match4 = this.matchUrlPattern(path, "relationship");
|
|
2262
|
-
if (match4) {
|
|
2263
|
-
return await this.processRelationshipCRUD(client, "delete", match4.type, match4.id, match4.relationship, query, requestBody);
|
|
2264
|
-
}
|
|
2265
|
-
const nestedDeleteMatch = this.matchUrlPattern(path, "nestedSingle");
|
|
2266
|
-
if (nestedDeleteMatch && this.nestedRoutes && this.resolveNestedRelation(nestedDeleteMatch.type, nestedDeleteMatch.relationship)?.isCollection) {
|
|
2267
|
-
return await this.processNestedDelete(client, nestedDeleteMatch.type, nestedDeleteMatch.id, nestedDeleteMatch.relationship, nestedDeleteMatch.childId);
|
|
2268
|
-
}
|
|
2269
|
-
match4 = this.matchUrlPattern(path, "single");
|
|
2270
|
-
if (match4) {
|
|
2271
|
-
return await this.processDelete(client, match4.type, match4.id);
|
|
2272
|
-
}
|
|
2273
|
-
return this.makeError("invalidPath");
|
|
2274
|
-
}
|
|
2275
|
-
default:
|
|
2276
|
-
return this.makeError("invalidPath");
|
|
2277
|
-
}
|
|
2278
|
-
} catch (err) {
|
|
2279
|
-
if (err instanceof InvalidValueError) {
|
|
2280
|
-
return this.makeError("invalidValue", err.message);
|
|
2281
|
-
} else if (err instanceof ORMError2) {
|
|
2282
|
-
return this.handleORMError(err);
|
|
2283
|
-
} else {
|
|
2284
|
-
return this.handleGenericError(err);
|
|
2285
|
-
}
|
|
2286
|
-
}
|
|
2287
|
-
}
|
|
2288
|
-
handleGenericError(err) {
|
|
2289
|
-
const resp = this.makeError("unknownError", err instanceof Error ? `${err.message}` : "Unknown error");
|
|
2290
|
-
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
2291
|
-
return resp;
|
|
2292
|
-
}
|
|
2293
|
-
async processProcedureRequest({ client, method, proc, query, requestBody }) {
|
|
2294
|
-
if (!proc) {
|
|
2295
|
-
return this.makeProcBadInputErrorResponse("missing procedure name");
|
|
2296
|
-
}
|
|
2297
|
-
const procDef = getProcedureDef(this.schema, proc);
|
|
2298
|
-
if (!procDef) {
|
|
2299
|
-
return this.makeProcBadInputErrorResponse(`unknown procedure: ${proc}`);
|
|
2300
|
-
}
|
|
2301
|
-
const isMutation = !!procDef.mutation;
|
|
2302
|
-
if (isMutation) {
|
|
2303
|
-
if (method !== "POST") {
|
|
2304
|
-
return this.makeProcBadInputErrorResponse("invalid request method, only POST is supported");
|
|
2305
|
-
}
|
|
2306
|
-
} else {
|
|
2307
|
-
if (method !== "GET") {
|
|
2308
|
-
return this.makeProcBadInputErrorResponse("invalid request method, only GET is supported");
|
|
2309
|
-
}
|
|
2310
|
-
}
|
|
2311
|
-
const argsPayload = method === "POST" ? requestBody : query;
|
|
2312
|
-
const { result: processedArgsPayload, error } = await processSuperJsonRequestPayload(argsPayload);
|
|
2313
|
-
if (error) {
|
|
2314
|
-
return this.makeProcBadInputErrorResponse(error);
|
|
2315
|
-
}
|
|
2316
|
-
let procInput;
|
|
2317
|
-
try {
|
|
2318
|
-
procInput = mapProcedureArgs(procDef, processedArgsPayload);
|
|
2319
|
-
} catch (err) {
|
|
2320
|
-
return this.makeProcBadInputErrorResponse(err instanceof Error ? err.message : "invalid procedure arguments");
|
|
2321
|
-
}
|
|
2322
|
-
try {
|
|
2323
|
-
log(this.log, "debug", () => `handling "$procs.${proc}" request`);
|
|
2324
|
-
const clientResult = await client.$procs?.[proc](procInput);
|
|
2325
|
-
const toSerialize = this.toPlainObject(clientResult);
|
|
2326
|
-
const { json, meta } = SuperJSON3.serialize(toSerialize);
|
|
2327
|
-
const responseBody = {
|
|
2328
|
-
data: json
|
|
2329
|
-
};
|
|
2330
|
-
if (meta) {
|
|
2331
|
-
responseBody.meta = {
|
|
2332
|
-
serialization: meta
|
|
2333
|
-
};
|
|
2334
|
-
}
|
|
2335
|
-
return {
|
|
2336
|
-
status: 200,
|
|
2337
|
-
body: responseBody
|
|
2338
|
-
};
|
|
2339
|
-
} catch (err) {
|
|
2340
|
-
log(this.log, "error", `error occurred when handling "$procs.${proc}" request`, err);
|
|
2341
|
-
if (err instanceof ORMError2) {
|
|
2342
|
-
throw err;
|
|
2343
|
-
}
|
|
2344
|
-
return this.makeProcGenericErrorResponse(err);
|
|
2345
|
-
}
|
|
2346
|
-
}
|
|
2347
|
-
makeProcBadInputErrorResponse(message) {
|
|
2348
|
-
const resp = this.makeError("invalidPayload", message, 400);
|
|
2349
|
-
log(this.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}`);
|
|
2350
|
-
return resp;
|
|
2351
|
-
}
|
|
2352
|
-
makeProcGenericErrorResponse(err) {
|
|
2353
|
-
const message = err instanceof Error ? err.message : "unknown error";
|
|
2354
|
-
const resp = this.makeError("unknownError", message, 500);
|
|
2355
|
-
log(this.log, "debug", () => `sending error response: ${safeJSONStringify(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
2356
|
-
return resp;
|
|
2357
|
-
}
|
|
2358
|
-
/**
|
|
2359
|
-
* Builds the ORM `args` object (include, select) shared by single-read operations.
|
|
2360
|
-
* Returns the args to pass to findUnique/findFirst and the resolved `include` list for serialization,
|
|
2361
|
-
* or an error response if query params are invalid.
|
|
2362
|
-
*/
|
|
2363
|
-
buildSingleReadArgs(type, query) {
|
|
2364
|
-
const args = {};
|
|
2365
|
-
this.includeRelationshipIds(type, args, "include");
|
|
2366
|
-
let include;
|
|
2367
|
-
if (query?.["include"]) {
|
|
2368
|
-
const { select: select2, error: error2, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
2369
|
-
if (error2) {
|
|
2370
|
-
return {
|
|
2371
|
-
args,
|
|
2372
|
-
include,
|
|
2373
|
-
error: error2
|
|
2374
|
-
};
|
|
2375
|
-
}
|
|
2376
|
-
if (select2) {
|
|
2377
|
-
args.include = {
|
|
2378
|
-
...args.include,
|
|
2379
|
-
...select2
|
|
2380
|
-
};
|
|
2381
|
-
}
|
|
2382
|
-
include = allIncludes;
|
|
2383
|
-
}
|
|
2384
|
-
const { select, error } = this.buildPartialSelect(type, query);
|
|
2385
|
-
if (error) return {
|
|
2386
|
-
args,
|
|
2387
|
-
include,
|
|
2388
|
-
error
|
|
2389
|
-
};
|
|
2390
|
-
if (select) {
|
|
2391
|
-
args.select = {
|
|
2392
|
-
...select,
|
|
2393
|
-
...args.select
|
|
2394
|
-
};
|
|
2395
|
-
if (args.include) {
|
|
2396
|
-
args.select = {
|
|
2397
|
-
...args.select,
|
|
2398
|
-
...args.include
|
|
2399
|
-
};
|
|
2400
|
-
args.include = void 0;
|
|
2401
|
-
}
|
|
2402
|
-
}
|
|
2403
|
-
return {
|
|
2404
|
-
args,
|
|
2405
|
-
include
|
|
2406
|
-
};
|
|
2407
|
-
}
|
|
2408
|
-
async processSingleRead(client, type, resourceId, query) {
|
|
2409
|
-
const typeInfo = this.getModelInfo(type);
|
|
2410
|
-
if (!typeInfo) {
|
|
2411
|
-
return this.makeUnsupportedModelError(type);
|
|
2412
|
-
}
|
|
2413
|
-
const { args, include, error } = this.buildSingleReadArgs(type, query);
|
|
2414
|
-
if (error) return error;
|
|
2415
|
-
args.where = this.makeIdFilter(typeInfo.idFields, resourceId);
|
|
2416
|
-
const entity = await client[type].findUnique(args);
|
|
2417
|
-
if (entity) {
|
|
2418
|
-
return {
|
|
2419
|
-
status: 200,
|
|
2420
|
-
body: await this.serializeItems(type, entity, {
|
|
2421
|
-
include
|
|
2422
|
-
})
|
|
2423
|
-
};
|
|
2424
|
-
} else {
|
|
2425
|
-
return this.makeError("notFound");
|
|
2426
|
-
}
|
|
2427
|
-
}
|
|
2428
|
-
async processFetchRelated(client, type, resourceId, relationship, query) {
|
|
2429
|
-
const typeInfo = this.getModelInfo(type);
|
|
2430
|
-
if (!typeInfo) {
|
|
2431
|
-
return this.makeUnsupportedModelError(type);
|
|
2432
|
-
}
|
|
2433
|
-
const relationInfo = typeInfo.relationships[relationship];
|
|
2434
|
-
if (!relationInfo) {
|
|
2435
|
-
return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
2436
|
-
}
|
|
2437
|
-
let select;
|
|
2438
|
-
let include;
|
|
2439
|
-
if (query?.["include"]) {
|
|
2440
|
-
const { select: relationSelect, error, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
2441
|
-
if (error) {
|
|
2442
|
-
return error;
|
|
2443
|
-
}
|
|
2444
|
-
include = allIncludes.filter((i) => i.startsWith(`${relationship}.`)).map((i) => i.substring(`${relationship}.`.length));
|
|
2445
|
-
select = relationSelect;
|
|
2446
|
-
}
|
|
2447
|
-
if (!select) {
|
|
2448
|
-
const { select: partialFields, error } = this.buildPartialSelect(lowerCaseFirst3(relationInfo.type), query);
|
|
2449
|
-
if (error) return error;
|
|
2450
|
-
select = partialFields ? {
|
|
2451
|
-
[relationship]: {
|
|
2452
|
-
select: {
|
|
2453
|
-
...partialFields
|
|
2454
|
-
}
|
|
2455
|
-
}
|
|
2456
|
-
} : {
|
|
2457
|
-
[relationship]: true
|
|
2458
|
-
};
|
|
2459
|
-
}
|
|
2460
|
-
const args = {
|
|
2461
|
-
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
2462
|
-
select
|
|
2463
|
-
};
|
|
2464
|
-
if (relationInfo.isCollection) {
|
|
2465
|
-
const error = this.injectRelationQuery(relationInfo.type, select, relationship, query);
|
|
2466
|
-
if (error) {
|
|
2467
|
-
return error;
|
|
2468
|
-
}
|
|
2469
|
-
}
|
|
2470
|
-
const entity = await client[type].findUnique(args);
|
|
2471
|
-
let paginator;
|
|
2472
|
-
if (entity?._count?.[relationship] !== void 0) {
|
|
2473
|
-
const total = entity?._count?.[relationship];
|
|
2474
|
-
const url = this.makeNormalizedUrl(`/${type}/${resourceId}/${relationship}`, query);
|
|
2475
|
-
const { offset, limit } = this.getPagination(query);
|
|
2476
|
-
paginator = this.makePaginator(url, offset, limit, total);
|
|
2477
|
-
}
|
|
2478
|
-
if (entity?.[relationship]) {
|
|
2479
|
-
const mappedType = this.mapModelName(type);
|
|
2480
|
-
return {
|
|
2481
|
-
status: 200,
|
|
2482
|
-
body: await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
2483
|
-
linkers: {
|
|
2484
|
-
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/${relationship}`)),
|
|
2485
|
-
paginator
|
|
2486
|
-
},
|
|
2487
|
-
include
|
|
2488
|
-
})
|
|
2489
|
-
};
|
|
2490
|
-
} else {
|
|
2491
|
-
return this.makeError("notFound");
|
|
2492
|
-
}
|
|
2493
|
-
}
|
|
2494
|
-
async processReadRelationship(client, type, resourceId, relationship, query) {
|
|
2495
|
-
const typeInfo = this.getModelInfo(type);
|
|
2496
|
-
if (!typeInfo) {
|
|
2497
|
-
return this.makeUnsupportedModelError(type);
|
|
2498
|
-
}
|
|
2499
|
-
const relationInfo = typeInfo.relationships[relationship];
|
|
2500
|
-
if (!relationInfo) {
|
|
2501
|
-
return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
2502
|
-
}
|
|
2503
|
-
const args = {
|
|
2504
|
-
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
2505
|
-
select: this.makeIdSelect(typeInfo.idFields)
|
|
2506
|
-
};
|
|
2507
|
-
args.select = {
|
|
2508
|
-
...args.select,
|
|
2509
|
-
[relationship]: {
|
|
2510
|
-
select: this.makeIdSelect(relationInfo.idFields)
|
|
2511
|
-
}
|
|
2512
|
-
};
|
|
2513
|
-
let paginator;
|
|
2514
|
-
if (relationInfo.isCollection) {
|
|
2515
|
-
const error = this.injectRelationQuery(relationInfo.type, args.select, relationship, query);
|
|
2516
|
-
if (error) {
|
|
2517
|
-
return error;
|
|
2518
|
-
}
|
|
2519
|
-
}
|
|
2520
|
-
const entity = await client[type].findUnique(args);
|
|
2521
|
-
const mappedType = this.mapModelName(type);
|
|
2522
|
-
if (entity?._count?.[relationship] !== void 0) {
|
|
2523
|
-
const total = entity?._count?.[relationship];
|
|
2524
|
-
const url = this.makeNormalizedUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`, query);
|
|
2525
|
-
const { offset, limit } = this.getPagination(query);
|
|
2526
|
-
paginator = this.makePaginator(url, offset, limit, total);
|
|
2527
|
-
}
|
|
2528
|
-
if (entity?.[relationship]) {
|
|
2529
|
-
const serialized = await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
2530
|
-
linkers: {
|
|
2531
|
-
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`)),
|
|
2532
|
-
paginator
|
|
2533
|
-
},
|
|
2534
|
-
onlyIdentifier: true
|
|
2535
|
-
});
|
|
2536
|
-
return {
|
|
2537
|
-
status: 200,
|
|
2538
|
-
body: serialized
|
|
2539
|
-
};
|
|
2540
|
-
} else {
|
|
2541
|
-
return this.makeError("notFound");
|
|
2542
|
-
}
|
|
2543
|
-
}
|
|
2544
|
-
async processCollectionRead(client, type, query) {
|
|
2545
|
-
const typeInfo = this.getModelInfo(type);
|
|
2546
|
-
if (!typeInfo) {
|
|
2547
|
-
return this.makeUnsupportedModelError(type);
|
|
2548
|
-
}
|
|
2549
|
-
const args = {};
|
|
2550
|
-
const { filter, error: filterError } = this.buildFilter(type, query);
|
|
2551
|
-
if (filterError) {
|
|
2552
|
-
return filterError;
|
|
2553
|
-
}
|
|
2554
|
-
if (filter) {
|
|
2555
|
-
args.where = filter;
|
|
2556
|
-
}
|
|
2557
|
-
const { sort, error: sortError } = this.buildSort(type, query);
|
|
2558
|
-
if (sortError) {
|
|
2559
|
-
return sortError;
|
|
2560
|
-
}
|
|
2561
|
-
if (sort) {
|
|
2562
|
-
args.orderBy = sort;
|
|
2563
|
-
}
|
|
2564
|
-
this.includeRelationshipIds(type, args, "include");
|
|
2565
|
-
let include;
|
|
2566
|
-
if (query?.["include"]) {
|
|
2567
|
-
const { select: select2, error: error2, allIncludes } = this.buildRelationSelect(type, query["include"], query);
|
|
2568
|
-
if (error2) {
|
|
2569
|
-
return error2;
|
|
2570
|
-
}
|
|
2571
|
-
if (select2) {
|
|
2572
|
-
args.include = {
|
|
2573
|
-
...args.include,
|
|
2574
|
-
...select2
|
|
2575
|
-
};
|
|
2576
|
-
}
|
|
2577
|
-
include = allIncludes;
|
|
2578
|
-
}
|
|
2579
|
-
const { select, error } = this.buildPartialSelect(type, query);
|
|
2580
|
-
if (error) return error;
|
|
2581
|
-
if (select) {
|
|
2582
|
-
args.select = {
|
|
2583
|
-
...select,
|
|
2584
|
-
...args.select
|
|
2585
|
-
};
|
|
2586
|
-
if (args.include) {
|
|
2587
|
-
args.select = {
|
|
2588
|
-
...args.select,
|
|
2589
|
-
...args.include
|
|
2590
|
-
};
|
|
2591
|
-
args.include = void 0;
|
|
2592
|
-
}
|
|
2593
|
-
}
|
|
2594
|
-
const { offset, limit } = this.getPagination(query);
|
|
2595
|
-
if (offset > 0) {
|
|
2596
|
-
args.skip = offset;
|
|
2597
|
-
}
|
|
2598
|
-
if (limit === Infinity) {
|
|
2599
|
-
const entities = await client[type].findMany(args);
|
|
2600
|
-
const mappedType = this.mapModelName(type);
|
|
2601
|
-
const body = await this.serializeItems(type, entities, {
|
|
2602
|
-
include,
|
|
2603
|
-
linkers: {
|
|
2604
|
-
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}`))
|
|
2605
|
-
}
|
|
2606
|
-
});
|
|
2607
|
-
const total = entities.length;
|
|
2608
|
-
body.meta = this.addTotalCountToMeta(body.meta, total);
|
|
2609
|
-
return {
|
|
2610
|
-
status: 200,
|
|
2611
|
-
body
|
|
2612
|
-
};
|
|
2613
|
-
} else {
|
|
2614
|
-
args.take = limit;
|
|
2615
|
-
const [entities, count] = await Promise.all([
|
|
2616
|
-
client[type].findMany(args),
|
|
2617
|
-
client[type].count({
|
|
2618
|
-
where: args.where ?? {}
|
|
2619
|
-
})
|
|
2620
|
-
]);
|
|
2621
|
-
const total = count;
|
|
2622
|
-
const mappedType = this.mapModelName(type);
|
|
2623
|
-
const url = this.makeNormalizedUrl(`/${mappedType}`, query);
|
|
2624
|
-
const options = {
|
|
2625
|
-
include,
|
|
2626
|
-
linkers: {
|
|
2627
|
-
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}`)),
|
|
2628
|
-
paginator: this.makePaginator(url, offset, limit, total)
|
|
2629
|
-
}
|
|
2630
|
-
};
|
|
2631
|
-
const body = await this.serializeItems(type, entities, options);
|
|
2632
|
-
body.meta = this.addTotalCountToMeta(body.meta, total);
|
|
2633
|
-
return {
|
|
2634
|
-
status: 200,
|
|
2635
|
-
body
|
|
2636
|
-
};
|
|
2637
|
-
}
|
|
2638
|
-
}
|
|
2639
|
-
/**
|
|
2640
|
-
* Builds link URL for a nested resource using parent type, parent ID, relation name, and optional child ID.
|
|
2641
|
-
* Uses the parent model name mapping for the parent segment; the relation name is used as-is.
|
|
2642
|
-
*/
|
|
2643
|
-
makeNestedLinkUrl(parentType, parentId, parentRelation, childId) {
|
|
2644
|
-
const mappedParentType = this.mapModelName(parentType);
|
|
2645
|
-
const base = `/${mappedParentType}/${parentId}/${parentRelation}`;
|
|
2646
|
-
return childId ? `${base}/${childId}` : base;
|
|
2647
|
-
}
|
|
2648
|
-
async processNestedSingleRead(client, parentType, parentId, parentRelation, childId, query) {
|
|
2649
|
-
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
2650
|
-
if (!resolved) {
|
|
2651
|
-
return this.makeError("invalidPath");
|
|
2652
|
-
}
|
|
2653
|
-
const { filter: nestedFilter, error: nestedError } = this.buildNestedParentFilter(parentType, parentId, parentRelation);
|
|
2654
|
-
if (nestedError) return nestedError;
|
|
2655
|
-
const childType = resolved.childType;
|
|
2656
|
-
const typeInfo = this.getModelInfo(childType);
|
|
2657
|
-
const { args, include, error } = this.buildSingleReadArgs(childType, query);
|
|
2658
|
-
if (error) return error;
|
|
2659
|
-
args.where = this.mergeFilters(this.makeIdFilter(typeInfo.idFields, childId), nestedFilter);
|
|
2660
|
-
const entity = await client[childType].findFirst(args);
|
|
2661
|
-
if (!entity) return this.makeError("notFound");
|
|
2662
|
-
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation, childId));
|
|
2663
|
-
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
2664
|
-
return {
|
|
2665
|
-
status: 200,
|
|
2666
|
-
body: await this.serializeItems(childType, entity, {
|
|
2667
|
-
include,
|
|
2668
|
-
linkers: {
|
|
2669
|
-
document: nestedLinker,
|
|
2670
|
-
resource: nestedLinker
|
|
2671
|
-
}
|
|
2672
|
-
})
|
|
2673
|
-
};
|
|
2674
|
-
}
|
|
2675
|
-
async processNestedCreate(client, parentType, parentId, parentRelation, _query, requestBody) {
|
|
2676
|
-
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
2677
|
-
if (!resolved) {
|
|
2678
|
-
return this.makeError("invalidPath");
|
|
2679
|
-
}
|
|
2680
|
-
const parentInfo = this.getModelInfo(parentType);
|
|
2681
|
-
const childType = resolved.childType;
|
|
2682
|
-
const childInfo = this.getModelInfo(childType);
|
|
2683
|
-
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
2684
|
-
if (error) return error;
|
|
2685
|
-
const createData = {
|
|
2686
|
-
...attributes
|
|
2687
|
-
};
|
|
2688
|
-
if (relationships) {
|
|
2689
|
-
for (const [key, data] of Object.entries(relationships)) {
|
|
2690
|
-
if (!data?.data) {
|
|
2691
|
-
return this.makeError("invalidRelationData");
|
|
2692
|
-
}
|
|
2693
|
-
if (key === resolved.reverseRelation) {
|
|
2694
|
-
return this.makeError("invalidPayload", `Relation "${key}" is controlled by the parent route and cannot be set in the request payload`);
|
|
2695
|
-
}
|
|
2696
|
-
const relationInfo = childInfo.relationships[key];
|
|
2697
|
-
if (!relationInfo) {
|
|
2698
|
-
return this.makeUnsupportedRelationshipError(childType, key, 400);
|
|
2699
|
-
}
|
|
2700
|
-
if (relationInfo.isCollection) {
|
|
2701
|
-
createData[key] = {
|
|
2702
|
-
connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id))
|
|
2703
|
-
};
|
|
2704
|
-
} else {
|
|
2705
|
-
if (typeof data.data !== "object") {
|
|
2706
|
-
return this.makeError("invalidRelationData");
|
|
2707
|
-
}
|
|
2708
|
-
createData[key] = {
|
|
2709
|
-
connect: this.makeIdConnect(relationInfo.idFields, data.data.id)
|
|
2710
|
-
};
|
|
2711
|
-
}
|
|
2712
|
-
}
|
|
2713
|
-
}
|
|
2714
|
-
const parentFkFields = Object.values(childInfo.fields).filter((f) => f.foreignKeyFor?.includes(resolved.reverseRelation));
|
|
2715
|
-
if (parentFkFields.some((f) => Object.prototype.hasOwnProperty.call(createData, f.name))) {
|
|
2716
|
-
return this.makeError("invalidPayload", `Relation "${resolved.reverseRelation}" is controlled by the parent route and cannot be set in the request payload`);
|
|
2717
|
-
}
|
|
2718
|
-
await client[parentType].update({
|
|
2719
|
-
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
2720
|
-
data: {
|
|
2721
|
-
[parentRelation]: {
|
|
2722
|
-
create: createData
|
|
2723
|
-
}
|
|
2724
|
-
}
|
|
2725
|
-
});
|
|
2726
|
-
const { filter: nestedFilter, error: filterError } = this.buildNestedParentFilter(parentType, parentId, parentRelation);
|
|
2727
|
-
if (filterError) return filterError;
|
|
2728
|
-
const fetchArgs = {
|
|
2729
|
-
where: nestedFilter
|
|
2730
|
-
};
|
|
2731
|
-
this.includeRelationshipIds(childType, fetchArgs, "include");
|
|
2732
|
-
if (childInfo.idFields[0]) {
|
|
2733
|
-
fetchArgs.orderBy = {
|
|
2734
|
-
[childInfo.idFields[0].name]: "desc"
|
|
2735
|
-
};
|
|
2736
|
-
}
|
|
2737
|
-
const entity = await client[childType].findFirst(fetchArgs);
|
|
2738
|
-
if (!entity) return this.makeError("notFound");
|
|
2739
|
-
const collectionPath = this.makeNestedLinkUrl(parentType, parentId, parentRelation);
|
|
2740
|
-
const resourceLinker = new tsjapi.Linker((item) => this.makeLinkUrl(`${collectionPath}/${this.getId(childInfo.name, item)}`));
|
|
2741
|
-
return {
|
|
2742
|
-
status: 201,
|
|
2743
|
-
body: await this.serializeItems(childType, entity, {
|
|
2744
|
-
linkers: {
|
|
2745
|
-
document: resourceLinker,
|
|
2746
|
-
resource: resourceLinker
|
|
2747
|
-
}
|
|
2748
|
-
})
|
|
2749
|
-
};
|
|
2750
|
-
}
|
|
2751
|
-
/**
|
|
2752
|
-
* Builds the ORM `data` payload for a nested update, shared by both to-many (childId present)
|
|
2753
|
-
* and to-one (childId absent) variants. Returns either `{ updateData }` or `{ error }`.
|
|
2754
|
-
*/
|
|
2755
|
-
buildNestedUpdatePayload(childType, typeInfo, rev, requestBody) {
|
|
2756
|
-
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
2757
|
-
if (error) return {
|
|
2758
|
-
error
|
|
2759
|
-
};
|
|
2760
|
-
const updateData = {
|
|
2761
|
-
...attributes
|
|
2762
|
-
};
|
|
2763
|
-
if (relationships && Object.prototype.hasOwnProperty.call(relationships, rev)) {
|
|
2764
|
-
return {
|
|
2765
|
-
error: this.makeError("invalidPayload", `Relation "${rev}" cannot be changed via a nested route`)
|
|
2766
|
-
};
|
|
2767
|
-
}
|
|
2768
|
-
const fkFields = Object.values(typeInfo.fields).filter((f) => f.foreignKeyFor?.includes(rev));
|
|
2769
|
-
if (fkFields.some((f) => Object.prototype.hasOwnProperty.call(updateData, f.name))) {
|
|
2770
|
-
return {
|
|
2771
|
-
error: this.makeError("invalidPayload", `Relation "${rev}" cannot be changed via a nested route`)
|
|
2772
|
-
};
|
|
2773
|
-
}
|
|
2774
|
-
if (relationships) {
|
|
2775
|
-
for (const [key, data] of Object.entries(relationships)) {
|
|
2776
|
-
if (!data?.data) {
|
|
2777
|
-
return {
|
|
2778
|
-
error: this.makeError("invalidRelationData")
|
|
2779
|
-
};
|
|
2780
|
-
}
|
|
2781
|
-
const relationInfo = typeInfo.relationships[key];
|
|
2782
|
-
if (!relationInfo) {
|
|
2783
|
-
return {
|
|
2784
|
-
error: this.makeUnsupportedRelationshipError(childType, key, 400)
|
|
2785
|
-
};
|
|
2786
|
-
}
|
|
2787
|
-
if (relationInfo.isCollection) {
|
|
2788
|
-
updateData[key] = {
|
|
2789
|
-
set: enumerate(data.data).map((item) => ({
|
|
2790
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: item.id
|
|
2791
|
-
}))
|
|
2792
|
-
};
|
|
2793
|
-
} else {
|
|
2794
|
-
if (typeof data.data !== "object") {
|
|
2795
|
-
return {
|
|
2796
|
-
error: this.makeError("invalidRelationData")
|
|
2797
|
-
};
|
|
2798
|
-
}
|
|
2799
|
-
updateData[key] = {
|
|
2800
|
-
connect: {
|
|
2801
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: data.data.id
|
|
2802
|
-
}
|
|
2803
|
-
};
|
|
2804
|
-
}
|
|
2805
|
-
}
|
|
2806
|
-
}
|
|
2807
|
-
return {
|
|
2808
|
-
updateData
|
|
2809
|
-
};
|
|
2810
|
-
}
|
|
2811
|
-
/**
|
|
2812
|
-
* Handles PATCH /:type/:id/:relationship/:childId (to-many) and
|
|
2813
|
-
* PATCH /:type/:id/:relationship (to-one, childId undefined).
|
|
2814
|
-
*/
|
|
2815
|
-
async processNestedUpdate(client, parentType, parentId, parentRelation, childId, _query, requestBody) {
|
|
2816
|
-
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
2817
|
-
if (!resolved) {
|
|
2818
|
-
return this.makeError("invalidPath");
|
|
2819
|
-
}
|
|
2820
|
-
const parentInfo = this.getModelInfo(parentType);
|
|
2821
|
-
const childType = resolved.childType;
|
|
2822
|
-
const typeInfo = this.getModelInfo(childType);
|
|
2823
|
-
const { updateData, error } = this.buildNestedUpdatePayload(childType, typeInfo, resolved.reverseRelation, requestBody);
|
|
2824
|
-
if (error) return error;
|
|
2825
|
-
if (childId) {
|
|
2826
|
-
await client[parentType].update({
|
|
2827
|
-
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
2828
|
-
data: {
|
|
2829
|
-
[parentRelation]: {
|
|
2830
|
-
update: {
|
|
2831
|
-
where: this.makeIdFilter(typeInfo.idFields, childId),
|
|
2832
|
-
data: updateData
|
|
2833
|
-
}
|
|
2834
|
-
}
|
|
2835
|
-
}
|
|
2836
|
-
});
|
|
2837
|
-
const fetchArgs = {
|
|
2838
|
-
where: this.makeIdFilter(typeInfo.idFields, childId)
|
|
2839
|
-
};
|
|
2840
|
-
this.includeRelationshipIds(childType, fetchArgs, "include");
|
|
2841
|
-
const entity = await client[childType].findUnique(fetchArgs);
|
|
2842
|
-
if (!entity) return this.makeError("notFound");
|
|
2843
|
-
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation, childId));
|
|
2844
|
-
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
2845
|
-
return {
|
|
2846
|
-
status: 200,
|
|
2847
|
-
body: await this.serializeItems(childType, entity, {
|
|
2848
|
-
linkers: {
|
|
2849
|
-
document: nestedLinker,
|
|
2850
|
-
resource: nestedLinker
|
|
2851
|
-
}
|
|
2852
|
-
})
|
|
2853
|
-
};
|
|
2854
|
-
} else {
|
|
2855
|
-
await client[parentType].update({
|
|
2856
|
-
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
2857
|
-
data: {
|
|
2858
|
-
[parentRelation]: {
|
|
2859
|
-
update: updateData
|
|
2860
|
-
}
|
|
2861
|
-
}
|
|
2862
|
-
});
|
|
2863
|
-
const childIncludeArgs = {};
|
|
2864
|
-
this.includeRelationshipIds(childType, childIncludeArgs, "include");
|
|
2865
|
-
const fetchArgs = {
|
|
2866
|
-
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
2867
|
-
select: {
|
|
2868
|
-
[parentRelation]: childIncludeArgs.include ? {
|
|
2869
|
-
include: childIncludeArgs.include
|
|
2870
|
-
} : true
|
|
2871
|
-
}
|
|
2872
|
-
};
|
|
2873
|
-
const parent = await client[parentType].findUnique(fetchArgs);
|
|
2874
|
-
const entity = parent?.[parentRelation];
|
|
2875
|
-
if (!entity) return this.makeError("notFound");
|
|
2876
|
-
const linkUrl = this.makeLinkUrl(this.makeNestedLinkUrl(parentType, parentId, parentRelation));
|
|
2877
|
-
const nestedLinker = new tsjapi.Linker(() => linkUrl);
|
|
2878
|
-
return {
|
|
2879
|
-
status: 200,
|
|
2880
|
-
body: await this.serializeItems(childType, entity, {
|
|
2881
|
-
linkers: {
|
|
2882
|
-
document: nestedLinker,
|
|
2883
|
-
resource: nestedLinker
|
|
2884
|
-
}
|
|
2885
|
-
})
|
|
2886
|
-
};
|
|
2887
|
-
}
|
|
2888
|
-
}
|
|
2889
|
-
async processNestedDelete(client, parentType, parentId, parentRelation, childId) {
|
|
2890
|
-
const resolved = this.resolveNestedRelation(parentType, parentRelation);
|
|
2891
|
-
if (!resolved) {
|
|
2892
|
-
return this.makeError("invalidPath");
|
|
2893
|
-
}
|
|
2894
|
-
const parentInfo = this.getModelInfo(parentType);
|
|
2895
|
-
const typeInfo = this.getModelInfo(resolved.childType);
|
|
2896
|
-
await client[parentType].update({
|
|
2897
|
-
where: this.makeIdFilter(parentInfo.idFields, parentId),
|
|
2898
|
-
data: {
|
|
2899
|
-
[parentRelation]: {
|
|
2900
|
-
delete: this.makeIdFilter(typeInfo.idFields, childId)
|
|
2901
|
-
}
|
|
2902
|
-
}
|
|
2903
|
-
});
|
|
2904
|
-
return {
|
|
2905
|
-
status: 200,
|
|
2906
|
-
body: {
|
|
2907
|
-
meta: {}
|
|
2908
|
-
}
|
|
2909
|
-
};
|
|
2910
|
-
}
|
|
2911
|
-
buildPartialSelect(type, query) {
|
|
2912
|
-
const selectFieldsQuery = query?.[`fields[${type}]`];
|
|
2913
|
-
if (!selectFieldsQuery) {
|
|
2914
|
-
return {
|
|
2915
|
-
select: void 0,
|
|
2916
|
-
error: void 0
|
|
2917
|
-
};
|
|
2918
|
-
}
|
|
2919
|
-
if (Array.isArray(selectFieldsQuery)) {
|
|
2920
|
-
return {
|
|
2921
|
-
select: void 0,
|
|
2922
|
-
error: this.makeError("duplicatedFieldsParameter", `duplicated fields query for type ${type}`)
|
|
2923
|
-
};
|
|
2924
|
-
}
|
|
2925
|
-
const typeInfo = this.getModelInfo(type);
|
|
2926
|
-
if (!typeInfo) {
|
|
2927
|
-
return {
|
|
2928
|
-
select: void 0,
|
|
2929
|
-
error: this.makeUnsupportedModelError(type)
|
|
2930
|
-
};
|
|
2931
|
-
}
|
|
2932
|
-
const selectFieldNames = selectFieldsQuery.split(",").filter((i) => i);
|
|
2933
|
-
const fields = selectFieldNames.reduce((acc, curr) => ({
|
|
2934
|
-
...acc,
|
|
2935
|
-
[curr]: true
|
|
2936
|
-
}), {});
|
|
2937
|
-
return {
|
|
2938
|
-
select: {
|
|
2939
|
-
...this.makeIdSelect(typeInfo.idFields),
|
|
2940
|
-
...fields
|
|
2941
|
-
}
|
|
2942
|
-
};
|
|
2943
|
-
}
|
|
2944
|
-
addTotalCountToMeta(meta, total) {
|
|
2945
|
-
return meta ? Object.assign(meta, {
|
|
2946
|
-
total
|
|
2947
|
-
}) : Object.assign({}, {
|
|
2948
|
-
total
|
|
2949
|
-
});
|
|
2950
|
-
}
|
|
2951
|
-
makePaginator(baseUrl, offset, limit, total) {
|
|
2952
|
-
if (limit === Infinity) {
|
|
2953
|
-
return void 0;
|
|
2954
|
-
}
|
|
2955
|
-
const totalPages = Math.ceil(total / limit);
|
|
2956
|
-
return new tsjapi.Paginator(() => ({
|
|
2957
|
-
first: this.replaceURLSearchParams(baseUrl, {
|
|
2958
|
-
"page[limit]": limit
|
|
2959
|
-
}),
|
|
2960
|
-
last: this.replaceURLSearchParams(baseUrl, {
|
|
2961
|
-
"page[offset]": (totalPages - 1) * limit
|
|
2962
|
-
}),
|
|
2963
|
-
prev: offset - limit >= 0 && offset - limit <= total - 1 ? this.replaceURLSearchParams(baseUrl, {
|
|
2964
|
-
"page[offset]": offset - limit,
|
|
2965
|
-
"page[limit]": limit
|
|
2966
|
-
}) : null,
|
|
2967
|
-
next: offset + limit <= total - 1 ? this.replaceURLSearchParams(baseUrl, {
|
|
2968
|
-
"page[offset]": offset + limit,
|
|
2969
|
-
"page[limit]": limit
|
|
2970
|
-
}) : null
|
|
2971
|
-
}));
|
|
2972
|
-
}
|
|
2973
|
-
processRequestBody(requestBody) {
|
|
2974
|
-
let body = requestBody;
|
|
2975
|
-
if (body.meta?.serialization) {
|
|
2976
|
-
body = SuperJSON3.deserialize({
|
|
2977
|
-
json: body,
|
|
2978
|
-
meta: body.meta.serialization
|
|
2979
|
-
});
|
|
2980
|
-
}
|
|
2981
|
-
const parseResult = this.createUpdatePayloadSchema.safeParse(body);
|
|
2982
|
-
if (!parseResult.success) {
|
|
2983
|
-
return {
|
|
2984
|
-
attributes: void 0,
|
|
2985
|
-
relationships: void 0,
|
|
2986
|
-
error: this.makeError("invalidPayload", getZodErrorMessage(parseResult.error))
|
|
2987
|
-
};
|
|
2988
|
-
}
|
|
2989
|
-
return {
|
|
2990
|
-
attributes: parseResult.data.data.attributes,
|
|
2991
|
-
relationships: parseResult.data.data.relationships,
|
|
2992
|
-
error: void 0
|
|
2993
|
-
};
|
|
2994
|
-
}
|
|
2995
|
-
async processCreate(client, type, _query, requestBody) {
|
|
2996
|
-
const typeInfo = this.getModelInfo(type);
|
|
2997
|
-
if (!typeInfo) {
|
|
2998
|
-
return this.makeUnsupportedModelError(type);
|
|
2999
|
-
}
|
|
3000
|
-
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
3001
|
-
if (error) {
|
|
3002
|
-
return error;
|
|
3003
|
-
}
|
|
3004
|
-
const createPayload = {
|
|
3005
|
-
data: {
|
|
3006
|
-
...attributes
|
|
3007
|
-
}
|
|
3008
|
-
};
|
|
3009
|
-
if (relationships) {
|
|
3010
|
-
for (const [key, data] of Object.entries(relationships)) {
|
|
3011
|
-
if (!data?.data) {
|
|
3012
|
-
return this.makeError("invalidRelationData");
|
|
3013
|
-
}
|
|
3014
|
-
const relationInfo = typeInfo.relationships[key];
|
|
3015
|
-
if (!relationInfo) {
|
|
3016
|
-
return this.makeUnsupportedRelationshipError(type, key, 400);
|
|
3017
|
-
}
|
|
3018
|
-
if (relationInfo.isCollection) {
|
|
3019
|
-
createPayload.data[key] = {
|
|
3020
|
-
connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id))
|
|
3021
|
-
};
|
|
3022
|
-
} else {
|
|
3023
|
-
if (typeof data.data !== "object") {
|
|
3024
|
-
return this.makeError("invalidRelationData");
|
|
3025
|
-
}
|
|
3026
|
-
createPayload.data[key] = {
|
|
3027
|
-
connect: this.makeIdConnect(relationInfo.idFields, data.data.id)
|
|
3028
|
-
};
|
|
3029
|
-
}
|
|
3030
|
-
createPayload.include = {
|
|
3031
|
-
...createPayload.include,
|
|
3032
|
-
[key]: {
|
|
3033
|
-
select: {
|
|
3034
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: true
|
|
3035
|
-
}
|
|
3036
|
-
}
|
|
3037
|
-
};
|
|
3038
|
-
}
|
|
3039
|
-
}
|
|
3040
|
-
this.includeRelationshipIds(type, createPayload, "include");
|
|
3041
|
-
const entity = await client[type].create(createPayload);
|
|
3042
|
-
return {
|
|
3043
|
-
status: 201,
|
|
3044
|
-
body: await this.serializeItems(type, entity)
|
|
3045
|
-
};
|
|
3046
|
-
}
|
|
3047
|
-
async processUpsert(client, type, _query, requestBody) {
|
|
3048
|
-
const typeInfo = this.getModelInfo(type);
|
|
3049
|
-
if (!typeInfo) {
|
|
3050
|
-
return this.makeUnsupportedModelError(type);
|
|
3051
|
-
}
|
|
3052
|
-
const modelName = typeInfo.name;
|
|
3053
|
-
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
3054
|
-
if (error) {
|
|
3055
|
-
return error;
|
|
3056
|
-
}
|
|
3057
|
-
const parseResult = this.upsertMetaSchema.safeParse(requestBody);
|
|
3058
|
-
if (parseResult.error) {
|
|
3059
|
-
return this.makeError("invalidPayload", getZodErrorMessage(parseResult.error));
|
|
3060
|
-
}
|
|
3061
|
-
const matchFields = parseResult.data.meta.matchFields;
|
|
3062
|
-
const uniqueFieldSets = this.getUniqueFieldSets(modelName);
|
|
3063
|
-
if (!uniqueFieldSets.some((set) => set.every((field) => matchFields.includes(field)))) {
|
|
3064
|
-
return this.makeError("invalidPayload", "Match fields must be unique fields", 400);
|
|
3065
|
-
}
|
|
3066
|
-
const upsertPayload = {
|
|
3067
|
-
where: this.makeUpsertWhere(matchFields, attributes, typeInfo),
|
|
3068
|
-
create: {
|
|
3069
|
-
...attributes
|
|
3070
|
-
},
|
|
3071
|
-
update: {
|
|
3072
|
-
...Object.fromEntries(Object.entries(attributes ?? {}).filter((e) => !matchFields.includes(e[0])))
|
|
3073
|
-
}
|
|
3074
|
-
};
|
|
3075
|
-
if (relationships) {
|
|
3076
|
-
for (const [key, data] of Object.entries(relationships)) {
|
|
3077
|
-
if (!data?.data) {
|
|
3078
|
-
return this.makeError("invalidRelationData");
|
|
3079
|
-
}
|
|
3080
|
-
const relationInfo = typeInfo.relationships[key];
|
|
3081
|
-
if (!relationInfo) {
|
|
3082
|
-
return this.makeUnsupportedRelationshipError(modelName, key, 400);
|
|
3083
|
-
}
|
|
3084
|
-
if (relationInfo.isCollection) {
|
|
3085
|
-
upsertPayload.create[key] = {
|
|
3086
|
-
connect: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id))
|
|
3087
|
-
};
|
|
3088
|
-
upsertPayload.update[key] = {
|
|
3089
|
-
set: enumerate(data.data).map((item) => this.makeIdConnect(relationInfo.idFields, item.id))
|
|
3090
|
-
};
|
|
3091
|
-
} else {
|
|
3092
|
-
if (typeof data.data !== "object") {
|
|
3093
|
-
return this.makeError("invalidRelationData");
|
|
3094
|
-
}
|
|
3095
|
-
upsertPayload.create[key] = {
|
|
3096
|
-
connect: this.makeIdConnect(relationInfo.idFields, data.data.id)
|
|
3097
|
-
};
|
|
3098
|
-
upsertPayload.update[key] = {
|
|
3099
|
-
connect: this.makeIdConnect(relationInfo.idFields, data.data.id)
|
|
3100
|
-
};
|
|
3101
|
-
}
|
|
3102
|
-
}
|
|
3103
|
-
}
|
|
3104
|
-
this.includeRelationshipIds(modelName, upsertPayload, "include");
|
|
3105
|
-
const entity = await client[modelName].upsert(upsertPayload);
|
|
3106
|
-
return {
|
|
3107
|
-
status: 201,
|
|
3108
|
-
body: await this.serializeItems(modelName, entity)
|
|
3109
|
-
};
|
|
3110
|
-
}
|
|
3111
|
-
getUniqueFieldSets(type) {
|
|
3112
|
-
const modelDef = this.requireModel(type);
|
|
3113
|
-
return Object.entries(modelDef.uniqueFields).map(([k, v]) => typeof v.type === "string" ? [
|
|
3114
|
-
k
|
|
3115
|
-
] : Object.keys(v));
|
|
3116
|
-
}
|
|
3117
|
-
async processRelationshipCRUD(client, mode, type, resourceId, relationship, _query, requestBody) {
|
|
3118
|
-
const typeInfo = this.getModelInfo(type);
|
|
3119
|
-
if (!typeInfo) {
|
|
3120
|
-
return this.makeUnsupportedModelError(type);
|
|
3121
|
-
}
|
|
3122
|
-
const relationInfo = typeInfo.relationships[relationship];
|
|
3123
|
-
if (!relationInfo) {
|
|
3124
|
-
return this.makeUnsupportedRelationshipError(type, relationship, 404);
|
|
3125
|
-
}
|
|
3126
|
-
if (!relationInfo.isCollection && mode !== "update") {
|
|
3127
|
-
return this.makeError("invalidVerb");
|
|
3128
|
-
}
|
|
3129
|
-
const updateArgs = {
|
|
3130
|
-
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
3131
|
-
select: {
|
|
3132
|
-
...typeInfo.idFields.reduce((acc, field) => ({
|
|
3133
|
-
...acc,
|
|
3134
|
-
[field.name]: true
|
|
3135
|
-
}), {}),
|
|
3136
|
-
[relationship]: {
|
|
3137
|
-
select: this.makeIdSelect(relationInfo.idFields)
|
|
3138
|
-
}
|
|
3139
|
-
}
|
|
3140
|
-
};
|
|
3141
|
-
if (!relationInfo.isCollection) {
|
|
3142
|
-
const parsed = this.updateSingleRelationSchema.safeParse(requestBody);
|
|
3143
|
-
if (!parsed.success) {
|
|
3144
|
-
return this.makeError("invalidPayload", getZodErrorMessage(parsed.error));
|
|
3145
|
-
}
|
|
3146
|
-
if (parsed.data.data === null) {
|
|
3147
|
-
if (!relationInfo.isOptional) {
|
|
3148
|
-
return this.makeError("invalidPayload");
|
|
3149
|
-
}
|
|
3150
|
-
updateArgs.data = {
|
|
3151
|
-
[relationship]: {
|
|
3152
|
-
disconnect: true
|
|
3153
|
-
}
|
|
3154
|
-
};
|
|
3155
|
-
} else {
|
|
3156
|
-
updateArgs.data = {
|
|
3157
|
-
[relationship]: {
|
|
3158
|
-
connect: this.makeIdConnect(relationInfo.idFields, parsed.data.data.id)
|
|
3159
|
-
}
|
|
3160
|
-
};
|
|
3161
|
-
}
|
|
3162
|
-
} else {
|
|
3163
|
-
const parsed = this.updateCollectionRelationSchema.safeParse(requestBody);
|
|
3164
|
-
if (!parsed.success) {
|
|
3165
|
-
return this.makeError("invalidPayload", getZodErrorMessage(parsed.error));
|
|
3166
|
-
}
|
|
3167
|
-
const relationVerb = mode === "create" ? "connect" : mode === "delete" ? "disconnect" : "set";
|
|
3168
|
-
updateArgs.data = {
|
|
3169
|
-
[relationship]: {
|
|
3170
|
-
[relationVerb]: enumerate(parsed.data.data).map((item) => this.makeIdFilter(relationInfo.idFields, item.id))
|
|
3171
|
-
}
|
|
3172
|
-
};
|
|
3173
|
-
}
|
|
3174
|
-
const entity = await client[type].update(updateArgs);
|
|
3175
|
-
const mappedType = this.mapModelName(type);
|
|
3176
|
-
const serialized = await this.serializeItems(relationInfo.type, entity[relationship], {
|
|
3177
|
-
linkers: {
|
|
3178
|
-
document: new tsjapi.Linker(() => this.makeLinkUrl(`/${mappedType}/${resourceId}/relationships/${relationship}`))
|
|
3179
|
-
},
|
|
3180
|
-
onlyIdentifier: true
|
|
3181
|
-
});
|
|
3182
|
-
return {
|
|
3183
|
-
status: 200,
|
|
3184
|
-
body: serialized
|
|
3185
|
-
};
|
|
3186
|
-
}
|
|
3187
|
-
async processUpdate(client, type, resourceId, _query, requestBody) {
|
|
3188
|
-
const typeInfo = this.getModelInfo(type);
|
|
3189
|
-
if (!typeInfo) {
|
|
3190
|
-
return this.makeUnsupportedModelError(type);
|
|
3191
|
-
}
|
|
3192
|
-
const { attributes, relationships, error } = this.processRequestBody(requestBody);
|
|
3193
|
-
if (error) {
|
|
3194
|
-
return error;
|
|
3195
|
-
}
|
|
3196
|
-
const updatePayload = {
|
|
3197
|
-
where: this.makeIdFilter(typeInfo.idFields, resourceId),
|
|
3198
|
-
data: {
|
|
3199
|
-
...attributes
|
|
3200
|
-
}
|
|
3201
|
-
};
|
|
3202
|
-
if (relationships) {
|
|
3203
|
-
for (const [key, data] of Object.entries(relationships)) {
|
|
3204
|
-
if (!data?.data) {
|
|
3205
|
-
return this.makeError("invalidRelationData");
|
|
3206
|
-
}
|
|
3207
|
-
const relationInfo = typeInfo.relationships[key];
|
|
3208
|
-
if (!relationInfo) {
|
|
3209
|
-
return this.makeUnsupportedRelationshipError(type, key, 400);
|
|
3210
|
-
}
|
|
3211
|
-
if (relationInfo.isCollection) {
|
|
3212
|
-
updatePayload.data[key] = {
|
|
3213
|
-
set: enumerate(data.data).map((item) => ({
|
|
3214
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: item.id
|
|
3215
|
-
}))
|
|
3216
|
-
};
|
|
3217
|
-
} else {
|
|
3218
|
-
if (typeof data.data !== "object") {
|
|
3219
|
-
return this.makeError("invalidRelationData");
|
|
3220
|
-
}
|
|
3221
|
-
updatePayload.data[key] = {
|
|
3222
|
-
connect: {
|
|
3223
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: data.data.id
|
|
3224
|
-
}
|
|
3225
|
-
};
|
|
3226
|
-
}
|
|
3227
|
-
updatePayload.include = {
|
|
3228
|
-
...updatePayload.include,
|
|
3229
|
-
[key]: {
|
|
3230
|
-
select: {
|
|
3231
|
-
[this.makeDefaultIdKey(relationInfo.idFields)]: true
|
|
3232
|
-
}
|
|
3233
|
-
}
|
|
3234
|
-
};
|
|
3235
|
-
}
|
|
3236
|
-
}
|
|
3237
|
-
this.includeRelationshipIds(type, updatePayload, "include");
|
|
3238
|
-
const entity = await client[type].update(updatePayload);
|
|
3239
|
-
return {
|
|
3240
|
-
status: 200,
|
|
3241
|
-
body: await this.serializeItems(type, entity)
|
|
3242
|
-
};
|
|
3243
|
-
}
|
|
3244
|
-
async processDelete(client, type, resourceId) {
|
|
3245
|
-
const typeInfo = this.getModelInfo(type);
|
|
3246
|
-
if (!typeInfo) {
|
|
3247
|
-
return this.makeUnsupportedModelError(type);
|
|
3248
|
-
}
|
|
3249
|
-
await client[type].delete({
|
|
3250
|
-
where: this.makeIdFilter(typeInfo.idFields, resourceId)
|
|
3251
|
-
});
|
|
3252
|
-
return {
|
|
3253
|
-
status: 200,
|
|
3254
|
-
body: {
|
|
3255
|
-
meta: {}
|
|
3256
|
-
}
|
|
3257
|
-
};
|
|
3258
|
-
}
|
|
3259
|
-
//#region utilities
|
|
3260
|
-
requireModel(model) {
|
|
3261
|
-
const modelDef = this.schema.models[model];
|
|
3262
|
-
if (!modelDef) {
|
|
3263
|
-
throw new Error(`Model ${model} is not defined in the schema`);
|
|
3264
|
-
}
|
|
3265
|
-
return modelDef;
|
|
3266
|
-
}
|
|
3267
|
-
getIdFields(model) {
|
|
3268
|
-
const modelDef = this.requireModel(model);
|
|
3269
|
-
const modelLower = lowerCaseFirst3(model);
|
|
3270
|
-
if (!(modelLower in this.externalIdMapping)) {
|
|
3271
|
-
return Object.values(modelDef.fields).filter((f) => modelDef.idFields.includes(f.name));
|
|
3272
|
-
}
|
|
3273
|
-
const externalIdName = this.externalIdMapping[modelLower];
|
|
3274
|
-
for (const [name, info] of Object.entries(modelDef.uniqueFields)) {
|
|
3275
|
-
if (name === externalIdName) {
|
|
3276
|
-
if (typeof info.type === "string") {
|
|
3277
|
-
return [
|
|
3278
|
-
this.requireField(model, name)
|
|
3279
|
-
];
|
|
3280
|
-
} else {
|
|
3281
|
-
return Object.keys(info).map((f) => this.requireField(model, f));
|
|
3282
|
-
}
|
|
3283
|
-
}
|
|
3284
|
-
}
|
|
3285
|
-
throw new Error(`Model ${model} does not have unique key ${externalIdName}`);
|
|
3286
|
-
}
|
|
3287
|
-
requireField(model, field) {
|
|
3288
|
-
const modelDef = this.requireModel(model);
|
|
3289
|
-
const fieldDef = modelDef.fields[field];
|
|
3290
|
-
if (!fieldDef) {
|
|
3291
|
-
throw new Error(`Field ${field} is not defined in model ${model}`);
|
|
3292
|
-
}
|
|
3293
|
-
return fieldDef;
|
|
3294
|
-
}
|
|
3295
|
-
buildTypeMap() {
|
|
3296
|
-
this.typeMap = {};
|
|
3297
|
-
for (const [model, { fields }] of Object.entries(this.schema.models)) {
|
|
3298
|
-
const idFields = this.getIdFields(model);
|
|
3299
|
-
if (idFields.length === 0) {
|
|
3300
|
-
log(this.options.log, "warn", `Not including model ${model} in the API because it has no ID field`);
|
|
3301
|
-
continue;
|
|
3302
|
-
}
|
|
3303
|
-
const modelInfo = this.typeMap[lowerCaseFirst3(model)] = {
|
|
3304
|
-
name: model,
|
|
3305
|
-
idFields,
|
|
3306
|
-
relationships: {},
|
|
3307
|
-
fields
|
|
3308
|
-
};
|
|
3309
|
-
for (const [field, fieldInfo] of Object.entries(fields)) {
|
|
3310
|
-
if (!fieldInfo.relation) {
|
|
3311
|
-
continue;
|
|
3312
|
-
}
|
|
3313
|
-
const fieldTypeIdFields = this.getIdFields(fieldInfo.type);
|
|
3314
|
-
if (fieldTypeIdFields.length === 0) {
|
|
3315
|
-
log(this.options.log, "warn", `Not including relation ${model}.${field} in the API because it has no ID field`);
|
|
3316
|
-
continue;
|
|
3317
|
-
}
|
|
3318
|
-
modelInfo.relationships[field] = {
|
|
3319
|
-
type: fieldInfo.type,
|
|
3320
|
-
idFields: fieldTypeIdFields,
|
|
3321
|
-
isCollection: !!fieldInfo.array,
|
|
3322
|
-
isOptional: !!fieldInfo.optional
|
|
3323
|
-
};
|
|
3324
|
-
}
|
|
3325
|
-
}
|
|
3326
|
-
}
|
|
3327
|
-
getModelInfo(model) {
|
|
3328
|
-
return this.typeMap[lowerCaseFirst3(model)];
|
|
3329
|
-
}
|
|
3330
|
-
makeLinkUrl(path) {
|
|
3331
|
-
return `${this.options.endpoint}${path}`;
|
|
3332
|
-
}
|
|
3333
|
-
buildSerializers() {
|
|
3334
|
-
const linkers = {};
|
|
3335
|
-
for (const model of Object.keys(this.schema.models)) {
|
|
3336
|
-
const ids = this.getIdFields(model);
|
|
3337
|
-
const modelLower = lowerCaseFirst3(model);
|
|
3338
|
-
const mappedModel = this.mapModelName(modelLower);
|
|
3339
|
-
if (ids.length < 1) {
|
|
3340
|
-
continue;
|
|
3341
|
-
}
|
|
3342
|
-
const linker = new tsjapi.Linker((items) => Array.isArray(items) ? this.makeLinkUrl(`/${mappedModel}`) : this.makeLinkUrl(`/${mappedModel}/${this.getId(model, items)}`));
|
|
3343
|
-
linkers[modelLower] = linker;
|
|
3344
|
-
let projection = {};
|
|
3345
|
-
const modelDef = this.requireModel(model);
|
|
3346
|
-
for (const [field, fieldDef] of Object.entries(modelDef.fields)) {
|
|
3347
|
-
if (fieldDef.relation) {
|
|
3348
|
-
projection[field] = 0;
|
|
3349
|
-
}
|
|
3350
|
-
}
|
|
3351
|
-
if (Object.keys(projection).length === 0) {
|
|
3352
|
-
projection = null;
|
|
3353
|
-
}
|
|
3354
|
-
const serializer = new tsjapi.Serializer(model, {
|
|
3355
|
-
version: "1.1",
|
|
3356
|
-
idKey: this.makeIdKey(ids),
|
|
3357
|
-
linkers: {
|
|
3358
|
-
resource: linker,
|
|
3359
|
-
document: linker
|
|
3360
|
-
},
|
|
3361
|
-
projection
|
|
3362
|
-
});
|
|
3363
|
-
this.serializers.set(modelLower, serializer);
|
|
3364
|
-
}
|
|
3365
|
-
for (const model of Object.keys(this.schema.models)) {
|
|
3366
|
-
const modelLower = lowerCaseFirst3(model);
|
|
3367
|
-
const serializer = this.serializers.get(modelLower);
|
|
3368
|
-
if (!serializer) {
|
|
3369
|
-
continue;
|
|
3370
|
-
}
|
|
3371
|
-
const relators = {};
|
|
3372
|
-
const modelDef = this.requireModel(model);
|
|
3373
|
-
for (const [field, fieldDef] of Object.entries(modelDef.fields)) {
|
|
3374
|
-
if (!fieldDef.relation) {
|
|
3375
|
-
continue;
|
|
3376
|
-
}
|
|
3377
|
-
const fieldSerializer = this.serializers.get(lowerCaseFirst3(fieldDef.type));
|
|
3378
|
-
if (!fieldSerializer) {
|
|
3379
|
-
continue;
|
|
3380
|
-
}
|
|
3381
|
-
const fieldIds = this.getIdFields(fieldDef.type);
|
|
3382
|
-
if (fieldIds.length > 0) {
|
|
3383
|
-
const mappedModel = this.mapModelName(modelLower);
|
|
3384
|
-
const relator = new tsjapi.Relator(async (data) => {
|
|
3385
|
-
return data[field];
|
|
3386
|
-
}, fieldSerializer, {
|
|
3387
|
-
relatedName: field,
|
|
3388
|
-
linkers: {
|
|
3389
|
-
related: new tsjapi.Linker((primary) => this.makeLinkUrl(`/${mappedModel}/${this.getId(model, primary)}/${field}`)),
|
|
3390
|
-
relationship: new tsjapi.Linker((primary) => this.makeLinkUrl(`/${mappedModel}/${this.getId(model, primary)}/relationships/${field}`))
|
|
3391
|
-
}
|
|
3392
|
-
});
|
|
3393
|
-
relators[field] = relator;
|
|
3394
|
-
}
|
|
3395
|
-
}
|
|
3396
|
-
serializer.setRelators(relators);
|
|
3397
|
-
}
|
|
3398
|
-
}
|
|
3399
|
-
getId(model, data) {
|
|
3400
|
-
if (!data) {
|
|
3401
|
-
return void 0;
|
|
3402
|
-
}
|
|
3403
|
-
const ids = this.getIdFields(model);
|
|
3404
|
-
if (ids.length === 0) {
|
|
3405
|
-
return void 0;
|
|
3406
|
-
} else {
|
|
3407
|
-
return data[this.makeIdKey(ids)];
|
|
3408
|
-
}
|
|
3409
|
-
}
|
|
3410
|
-
async serializeItems(model, items, options) {
|
|
3411
|
-
model = lowerCaseFirst3(model);
|
|
3412
|
-
const serializer = this.serializers.get(model);
|
|
3413
|
-
if (!serializer) {
|
|
3414
|
-
throw new Error(`serializer not found for model ${model}`);
|
|
3415
|
-
}
|
|
3416
|
-
const itemsWithId = clone(items);
|
|
3417
|
-
this.injectCompoundId(model, itemsWithId);
|
|
3418
|
-
const serialized = await serializer.serialize(itemsWithId, options);
|
|
3419
|
-
const plainResult = this.toPlainObject(serialized);
|
|
3420
|
-
const { json, meta } = SuperJSON3.serialize(plainResult);
|
|
3421
|
-
const result = json;
|
|
3422
|
-
if (meta) {
|
|
3423
|
-
result.meta = {
|
|
3424
|
-
...result.meta,
|
|
3425
|
-
serialization: meta
|
|
3426
|
-
};
|
|
3427
|
-
}
|
|
3428
|
-
return result;
|
|
3429
|
-
}
|
|
3430
|
-
injectCompoundId(model, items) {
|
|
3431
|
-
const typeInfo = this.getModelInfo(model);
|
|
3432
|
-
if (!typeInfo) {
|
|
3433
|
-
return;
|
|
3434
|
-
}
|
|
3435
|
-
enumerate(items).forEach((item) => {
|
|
3436
|
-
if (!item) {
|
|
3437
|
-
return;
|
|
3438
|
-
}
|
|
3439
|
-
if (typeInfo.idFields.length > 1) {
|
|
3440
|
-
item[this.makeIdKey(typeInfo.idFields)] = this.makeCompoundId(typeInfo.idFields, item);
|
|
3441
|
-
}
|
|
3442
|
-
for (const [key, value] of Object.entries(item)) {
|
|
3443
|
-
if (typeInfo.relationships[key]) {
|
|
3444
|
-
this.injectCompoundId(typeInfo.relationships[key].type, value);
|
|
3445
|
-
}
|
|
3446
|
-
}
|
|
3447
|
-
});
|
|
3448
|
-
}
|
|
3449
|
-
toPlainObject(data) {
|
|
3450
|
-
if (data === void 0 || data === null) {
|
|
3451
|
-
return data;
|
|
3452
|
-
}
|
|
3453
|
-
if (Array.isArray(data)) {
|
|
3454
|
-
return data.map((item) => this.toPlainObject(item));
|
|
3455
|
-
}
|
|
3456
|
-
if (typeof data === "object") {
|
|
3457
|
-
if (typeof data.toJSON === "function") {
|
|
3458
|
-
return data.toJSON();
|
|
3459
|
-
}
|
|
3460
|
-
const result = {};
|
|
3461
|
-
for (const [field, value] of Object.entries(data)) {
|
|
3462
|
-
if (value === void 0 || typeof value === "function") {
|
|
3463
|
-
continue;
|
|
3464
|
-
} else if (field === "attributes") {
|
|
3465
|
-
result[field] = value;
|
|
3466
|
-
} else {
|
|
3467
|
-
result[field] = this.toPlainObject(value);
|
|
3468
|
-
}
|
|
3469
|
-
}
|
|
3470
|
-
return result;
|
|
3471
|
-
}
|
|
3472
|
-
return data;
|
|
3473
|
-
}
|
|
3474
|
-
replaceURLSearchParams(url, params) {
|
|
3475
|
-
const r = new URL(url);
|
|
3476
|
-
for (const [key, value] of Object.entries(params)) {
|
|
3477
|
-
r.searchParams.set(key, value.toString());
|
|
3478
|
-
}
|
|
3479
|
-
return r.toString();
|
|
3480
|
-
}
|
|
3481
|
-
makeIdFilter(idFields, resourceId, nested = true) {
|
|
3482
|
-
const decodedId = decodeURIComponent(resourceId);
|
|
3483
|
-
if (idFields.length === 1) {
|
|
3484
|
-
return {
|
|
3485
|
-
[idFields[0].name]: this.coerce(idFields[0], decodedId)
|
|
3486
|
-
};
|
|
3487
|
-
} else if (nested) {
|
|
3488
|
-
return {
|
|
3489
|
-
// TODO: support `@@id` with custom name
|
|
3490
|
-
[idFields.map((idf) => idf.name).join(DEFAULT_ID_DIVIDER)]: idFields.reduce((acc, curr, idx) => ({
|
|
3491
|
-
...acc,
|
|
3492
|
-
[curr.name]: this.coerce(curr, decodedId.split(this.idDivider)[idx])
|
|
3493
|
-
}), {})
|
|
3494
|
-
};
|
|
3495
|
-
} else {
|
|
3496
|
-
return idFields.reduce((acc, curr, idx) => ({
|
|
3497
|
-
...acc,
|
|
3498
|
-
[curr.name]: this.coerce(curr, decodedId.split(this.idDivider)[idx])
|
|
3499
|
-
}), {});
|
|
3500
|
-
}
|
|
3501
|
-
}
|
|
3502
|
-
makeIdSelect(idFields) {
|
|
3503
|
-
if (idFields.length === 0) {
|
|
3504
|
-
throw this.errors["noId"];
|
|
3505
|
-
}
|
|
3506
|
-
return idFields.reduce((acc, curr) => ({
|
|
3507
|
-
...acc,
|
|
3508
|
-
[curr.name]: true
|
|
3509
|
-
}), {});
|
|
3510
|
-
}
|
|
3511
|
-
makeIdConnect(idFields, id) {
|
|
3512
|
-
if (idFields.length === 1) {
|
|
3513
|
-
return {
|
|
3514
|
-
[idFields[0].name]: this.coerce(idFields[0], id)
|
|
3515
|
-
};
|
|
3516
|
-
} else {
|
|
3517
|
-
return {
|
|
3518
|
-
[this.makeDefaultIdKey(idFields)]: idFields.reduce((acc, curr, idx) => ({
|
|
3519
|
-
...acc,
|
|
3520
|
-
[curr.name]: this.coerce(curr, `${id}`.split(this.idDivider)[idx])
|
|
3521
|
-
}), {})
|
|
3522
|
-
};
|
|
3523
|
-
}
|
|
3524
|
-
}
|
|
3525
|
-
makeIdKey(idFields) {
|
|
3526
|
-
return idFields.map((idf) => idf.name).join(this.idDivider);
|
|
3527
|
-
}
|
|
3528
|
-
makeDefaultIdKey(idFields) {
|
|
3529
|
-
return idFields.map((idf) => idf.name).join(DEFAULT_ID_DIVIDER);
|
|
3530
|
-
}
|
|
3531
|
-
makeCompoundId(idFields, item) {
|
|
3532
|
-
return idFields.map((idf) => item[idf.name]).join(this.idDivider);
|
|
3533
|
-
}
|
|
3534
|
-
makeUpsertWhere(matchFields, attributes, typeInfo) {
|
|
3535
|
-
const where = matchFields.reduce((acc, field) => {
|
|
3536
|
-
acc[field] = attributes[field] ?? null;
|
|
3537
|
-
return acc;
|
|
3538
|
-
}, {});
|
|
3539
|
-
if (typeInfo.idFields.length > 1 && matchFields.some((mf) => typeInfo.idFields.map((idf) => idf.name).includes(mf))) {
|
|
3540
|
-
return {
|
|
3541
|
-
[this.makeDefaultIdKey(typeInfo.idFields)]: where
|
|
3542
|
-
};
|
|
3543
|
-
}
|
|
3544
|
-
return where;
|
|
3545
|
-
}
|
|
3546
|
-
includeRelationshipIds(model, args, mode) {
|
|
3547
|
-
const typeInfo = this.getModelInfo(model);
|
|
3548
|
-
if (!typeInfo) {
|
|
3549
|
-
return;
|
|
3550
|
-
}
|
|
3551
|
-
for (const [relation, relationInfo] of Object.entries(typeInfo.relationships)) {
|
|
3552
|
-
args[mode] = {
|
|
3553
|
-
...args[mode],
|
|
3554
|
-
[relation]: {
|
|
3555
|
-
select: this.makeIdSelect(relationInfo.idFields)
|
|
3556
|
-
}
|
|
3557
|
-
};
|
|
3558
|
-
}
|
|
3559
|
-
}
|
|
3560
|
-
coerce(fieldDef, value) {
|
|
3561
|
-
if (typeof value === "string") {
|
|
3562
|
-
if (fieldDef.attributes?.some((attr) => attr.name === "@json")) {
|
|
3563
|
-
try {
|
|
3564
|
-
return JSON.parse(value);
|
|
3565
|
-
} catch {
|
|
3566
|
-
throw new InvalidValueError(`invalid JSON value: ${value}`);
|
|
3567
|
-
}
|
|
3568
|
-
}
|
|
3569
|
-
const type = fieldDef.type;
|
|
3570
|
-
if (type === "Int") {
|
|
3571
|
-
const parsed = parseInt(value);
|
|
3572
|
-
if (isNaN(parsed)) {
|
|
3573
|
-
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
3574
|
-
}
|
|
3575
|
-
return parsed;
|
|
3576
|
-
} else if (type === "BigInt") {
|
|
3577
|
-
try {
|
|
3578
|
-
return BigInt(value);
|
|
3579
|
-
} catch {
|
|
3580
|
-
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
3581
|
-
}
|
|
3582
|
-
} else if (type === "Float") {
|
|
3583
|
-
const parsed = parseFloat(value);
|
|
3584
|
-
if (isNaN(parsed)) {
|
|
3585
|
-
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
3586
|
-
}
|
|
3587
|
-
return parsed;
|
|
3588
|
-
} else if (type === "Decimal") {
|
|
3589
|
-
try {
|
|
3590
|
-
return new Decimal2(value);
|
|
3591
|
-
} catch {
|
|
3592
|
-
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
3593
|
-
}
|
|
3594
|
-
} else if (type === "Boolean") {
|
|
3595
|
-
if (value === "true") {
|
|
3596
|
-
return true;
|
|
3597
|
-
} else if (value === "false") {
|
|
3598
|
-
return false;
|
|
3599
|
-
} else {
|
|
3600
|
-
throw new InvalidValueError(`invalid ${type} value: ${value}`);
|
|
3601
|
-
}
|
|
3602
|
-
}
|
|
3603
|
-
}
|
|
3604
|
-
return value;
|
|
3605
|
-
}
|
|
3606
|
-
makeNormalizedUrl(path, query) {
|
|
3607
|
-
const url = new URL(this.makeLinkUrl(path));
|
|
3608
|
-
for (const [key, value] of Object.entries(query ?? {})) {
|
|
3609
|
-
if (key.startsWith("filter[") || key.startsWith("sort[") || key === "include" || key.startsWith("include[") || key.startsWith("fields[")) {
|
|
3610
|
-
for (const v of enumerate(value)) {
|
|
3611
|
-
url.searchParams.append(key, v);
|
|
3612
|
-
}
|
|
3613
|
-
}
|
|
3614
|
-
}
|
|
3615
|
-
return url.toString();
|
|
3616
|
-
}
|
|
3617
|
-
getPagination(query) {
|
|
3618
|
-
if (!query) {
|
|
3619
|
-
return {
|
|
3620
|
-
offset: 0,
|
|
3621
|
-
limit: this.options.pageSize ?? DEFAULT_PAGE_SIZE
|
|
3622
|
-
};
|
|
3623
|
-
}
|
|
3624
|
-
let offset = 0;
|
|
3625
|
-
if (query["page[offset]"]) {
|
|
3626
|
-
const value = query["page[offset]"];
|
|
3627
|
-
const offsetText = Array.isArray(value) ? value[value.length - 1] : value;
|
|
3628
|
-
offset = parseInt(offsetText);
|
|
3629
|
-
if (isNaN(offset) || offset < 0) {
|
|
3630
|
-
offset = 0;
|
|
3631
|
-
}
|
|
3632
|
-
}
|
|
3633
|
-
let pageSizeOption = this.options.pageSize ?? DEFAULT_PAGE_SIZE;
|
|
3634
|
-
if (pageSizeOption <= 0) {
|
|
3635
|
-
pageSizeOption = DEFAULT_PAGE_SIZE;
|
|
3636
|
-
}
|
|
3637
|
-
let limit = pageSizeOption;
|
|
3638
|
-
if (query["page[limit]"]) {
|
|
3639
|
-
const value = query["page[limit]"];
|
|
3640
|
-
const limitText = Array.isArray(value) ? value[value.length - 1] : value;
|
|
3641
|
-
limit = parseInt(limitText);
|
|
3642
|
-
if (isNaN(limit) || limit <= 0) {
|
|
3643
|
-
limit = pageSizeOption;
|
|
3644
|
-
}
|
|
3645
|
-
limit = Math.min(pageSizeOption, limit);
|
|
3646
|
-
}
|
|
3647
|
-
return {
|
|
3648
|
-
offset,
|
|
3649
|
-
limit
|
|
3650
|
-
};
|
|
3651
|
-
}
|
|
3652
|
-
buildFilter(type, query) {
|
|
3653
|
-
if (!query) {
|
|
3654
|
-
return {
|
|
3655
|
-
filter: void 0,
|
|
3656
|
-
error: void 0
|
|
3657
|
-
};
|
|
3658
|
-
}
|
|
3659
|
-
const typeInfo = this.getModelInfo(type);
|
|
3660
|
-
if (!typeInfo) {
|
|
3661
|
-
return {
|
|
3662
|
-
filter: void 0,
|
|
3663
|
-
error: this.makeUnsupportedModelError(type)
|
|
3664
|
-
};
|
|
3665
|
-
}
|
|
3666
|
-
const items = [];
|
|
3667
|
-
for (const [key, value] of Object.entries(query)) {
|
|
3668
|
-
if (!value) {
|
|
3669
|
-
continue;
|
|
3670
|
-
}
|
|
3671
|
-
const match4 = key.match(this.filterParamPattern);
|
|
3672
|
-
if (!match4 || !match4.groups || !match4.groups["match"]) {
|
|
3673
|
-
continue;
|
|
3674
|
-
}
|
|
3675
|
-
const filterKeys = match4.groups["match"].replaceAll(/[[\]]/g, " ").split(" ").filter((i) => i);
|
|
3676
|
-
if (!filterKeys.length) {
|
|
3677
|
-
continue;
|
|
3678
|
-
}
|
|
3679
|
-
const item = {};
|
|
3680
|
-
let curr = item;
|
|
3681
|
-
let currType = typeInfo;
|
|
3682
|
-
for (const filterValue of enumerate(value)) {
|
|
3683
|
-
for (let i = 0; i < filterKeys.length; i++) {
|
|
3684
|
-
let filterKey = filterKeys[i];
|
|
3685
|
-
let filterOp;
|
|
3686
|
-
const pos = filterKey.indexOf("$");
|
|
3687
|
-
if (pos > 0) {
|
|
3688
|
-
filterOp = filterKey.substring(pos + 1);
|
|
3689
|
-
filterKey = filterKey.substring(0, pos);
|
|
3690
|
-
}
|
|
3691
|
-
if (!!filterOp && !FilterOperations.includes(filterOp)) {
|
|
3692
|
-
return {
|
|
3693
|
-
filter: void 0,
|
|
3694
|
-
error: this.makeError("invalidFilter", `invalid filter operation: ${filterOp}`)
|
|
3695
|
-
};
|
|
3696
|
-
}
|
|
3697
|
-
const idFields = this.getIdFields(currType.name);
|
|
3698
|
-
const fieldDef = filterKey === "id" ? Object.values(currType.fields).find((f) => idFields.some((idf) => idf.name === f.name)) : currType.fields[filterKey];
|
|
3699
|
-
if (!fieldDef) {
|
|
3700
|
-
return {
|
|
3701
|
-
filter: void 0,
|
|
3702
|
-
error: this.makeError("invalidFilter")
|
|
3703
|
-
};
|
|
3704
|
-
}
|
|
3705
|
-
if (!fieldDef.relation) {
|
|
3706
|
-
if (i !== filterKeys.length - 1) {
|
|
3707
|
-
return {
|
|
3708
|
-
filter: void 0,
|
|
3709
|
-
error: this.makeError("invalidFilter")
|
|
3710
|
-
};
|
|
3711
|
-
}
|
|
3712
|
-
curr[fieldDef.name] = this.makeFilterValue(fieldDef, filterValue, filterOp);
|
|
3713
|
-
} else {
|
|
3714
|
-
if (i === filterKeys.length - 1) {
|
|
3715
|
-
curr[fieldDef.name] = this.makeFilterValue(fieldDef, filterValue, filterOp);
|
|
3716
|
-
} else {
|
|
3717
|
-
if (fieldDef.array) {
|
|
3718
|
-
curr[fieldDef.name] = {
|
|
3719
|
-
some: {}
|
|
3720
|
-
};
|
|
3721
|
-
curr = curr[fieldDef.name].some;
|
|
3722
|
-
} else {
|
|
3723
|
-
curr = curr[fieldDef.name] = {};
|
|
3724
|
-
}
|
|
3725
|
-
currType = this.getModelInfo(fieldDef.type);
|
|
3726
|
-
}
|
|
3727
|
-
}
|
|
3728
|
-
}
|
|
3729
|
-
items.push(item);
|
|
3730
|
-
}
|
|
3731
|
-
}
|
|
3732
|
-
if (items.length === 0) {
|
|
3733
|
-
return {
|
|
3734
|
-
filter: void 0,
|
|
3735
|
-
error: void 0
|
|
3736
|
-
};
|
|
3737
|
-
} else {
|
|
3738
|
-
return {
|
|
3739
|
-
filter: items.length === 1 ? items[0] : {
|
|
3740
|
-
AND: items
|
|
3741
|
-
},
|
|
3742
|
-
error: void 0
|
|
3743
|
-
};
|
|
3744
|
-
}
|
|
3745
|
-
}
|
|
3746
|
-
buildSort(type, query) {
|
|
3747
|
-
if (!query?.["sort"]) {
|
|
3748
|
-
return {
|
|
3749
|
-
sort: void 0,
|
|
3750
|
-
error: void 0
|
|
3751
|
-
};
|
|
3752
|
-
}
|
|
3753
|
-
const typeInfo = this.getModelInfo(type);
|
|
3754
|
-
if (!typeInfo) {
|
|
3755
|
-
return {
|
|
3756
|
-
sort: void 0,
|
|
3757
|
-
error: this.makeUnsupportedModelError(type)
|
|
3758
|
-
};
|
|
3759
|
-
}
|
|
3760
|
-
const result = [];
|
|
3761
|
-
for (const sortSpec of enumerate(query["sort"])) {
|
|
3762
|
-
const sortFields = sortSpec.split(",").filter((i) => i);
|
|
3763
|
-
for (const sortField of sortFields) {
|
|
3764
|
-
const dir = sortField.startsWith("-") ? "desc" : "asc";
|
|
3765
|
-
const cleanedSortField = sortField.startsWith("-") ? sortField.substring(1) : sortField;
|
|
3766
|
-
const parts = cleanedSortField.split(".").filter((i) => i);
|
|
3767
|
-
const sortItem = {};
|
|
3768
|
-
let curr = sortItem;
|
|
3769
|
-
let currType = typeInfo;
|
|
3770
|
-
for (let i = 0; i < parts.length; i++) {
|
|
3771
|
-
const part = parts[i];
|
|
3772
|
-
const fieldInfo = currType.fields[part];
|
|
3773
|
-
if (!fieldInfo || fieldInfo.array) {
|
|
3774
|
-
return {
|
|
3775
|
-
sort: void 0,
|
|
3776
|
-
error: this.makeError("invalidSort", "sorting by array field is not supported")
|
|
3777
|
-
};
|
|
3778
|
-
}
|
|
3779
|
-
if (i === parts.length - 1) {
|
|
3780
|
-
if (fieldInfo.relation) {
|
|
3781
|
-
const relationType = this.getModelInfo(fieldInfo.type);
|
|
3782
|
-
if (!relationType) {
|
|
3783
|
-
return {
|
|
3784
|
-
sort: void 0,
|
|
3785
|
-
error: this.makeUnsupportedModelError(fieldInfo.type)
|
|
3786
|
-
};
|
|
3787
|
-
}
|
|
3788
|
-
curr[fieldInfo.name] = relationType.idFields.reduce((acc, idField) => {
|
|
3789
|
-
acc[idField.name] = dir;
|
|
3790
|
-
return acc;
|
|
3791
|
-
}, {});
|
|
3792
|
-
} else {
|
|
3793
|
-
curr[fieldInfo.name] = dir;
|
|
3794
|
-
}
|
|
3795
|
-
} else {
|
|
3796
|
-
if (!fieldInfo.relation) {
|
|
3797
|
-
return {
|
|
3798
|
-
sort: void 0,
|
|
3799
|
-
error: this.makeError("invalidSort", "intermediate sort segments must be relationships")
|
|
3800
|
-
};
|
|
3801
|
-
}
|
|
3802
|
-
curr = curr[fieldInfo.name] = {};
|
|
3803
|
-
currType = this.getModelInfo(fieldInfo.type);
|
|
3804
|
-
if (!currType) {
|
|
3805
|
-
return {
|
|
3806
|
-
sort: void 0,
|
|
3807
|
-
error: this.makeUnsupportedModelError(fieldInfo.type)
|
|
3808
|
-
};
|
|
3809
|
-
}
|
|
3810
|
-
}
|
|
3811
|
-
}
|
|
3812
|
-
result.push(sortItem);
|
|
3813
|
-
}
|
|
3814
|
-
}
|
|
3815
|
-
return {
|
|
3816
|
-
sort: result,
|
|
3817
|
-
error: void 0
|
|
3818
|
-
};
|
|
3819
|
-
}
|
|
3820
|
-
buildRelationSelect(type, include, query) {
|
|
3821
|
-
const typeInfo = this.getModelInfo(type);
|
|
3822
|
-
if (!typeInfo) {
|
|
3823
|
-
return {
|
|
3824
|
-
select: void 0,
|
|
3825
|
-
error: this.makeUnsupportedModelError(type)
|
|
3826
|
-
};
|
|
3827
|
-
}
|
|
3828
|
-
const result = {};
|
|
3829
|
-
const allIncludes = [];
|
|
3830
|
-
for (const includeItem of enumerate(include)) {
|
|
3831
|
-
const inclusions = includeItem.split(",").filter((i) => i);
|
|
3832
|
-
for (const inclusion of inclusions) {
|
|
3833
|
-
allIncludes.push(inclusion);
|
|
3834
|
-
const parts = inclusion.split(".");
|
|
3835
|
-
let currPayload = result;
|
|
3836
|
-
let currType = typeInfo;
|
|
3837
|
-
for (let i = 0; i < parts.length; i++) {
|
|
3838
|
-
const relation = parts[i];
|
|
3839
|
-
const relationInfo = currType.relationships[relation];
|
|
3840
|
-
if (!relationInfo) {
|
|
3841
|
-
return {
|
|
3842
|
-
select: void 0,
|
|
3843
|
-
error: this.makeUnsupportedRelationshipError(type, relation, 400)
|
|
3844
|
-
};
|
|
3845
|
-
}
|
|
3846
|
-
currType = this.getModelInfo(relationInfo.type);
|
|
3847
|
-
if (!currType) {
|
|
3848
|
-
return {
|
|
3849
|
-
select: void 0,
|
|
3850
|
-
error: this.makeUnsupportedModelError(relationInfo.type)
|
|
3851
|
-
};
|
|
3852
|
-
}
|
|
3853
|
-
const { select, error } = this.buildPartialSelect(lowerCaseFirst3(relationInfo.type), query);
|
|
3854
|
-
if (error) return {
|
|
3855
|
-
select: void 0,
|
|
3856
|
-
error
|
|
3857
|
-
};
|
|
3858
|
-
if (i !== parts.length - 1) {
|
|
3859
|
-
if (select) {
|
|
3860
|
-
currPayload[relation] = {
|
|
3861
|
-
select: {
|
|
3862
|
-
...select
|
|
3863
|
-
}
|
|
3864
|
-
};
|
|
3865
|
-
currPayload = currPayload[relation].select;
|
|
3866
|
-
} else {
|
|
3867
|
-
currPayload[relation] = {
|
|
3868
|
-
include: {
|
|
3869
|
-
...currPayload[relation]?.include
|
|
3870
|
-
}
|
|
3871
|
-
};
|
|
3872
|
-
currPayload = currPayload[relation].include;
|
|
3873
|
-
}
|
|
3874
|
-
} else {
|
|
3875
|
-
currPayload[relation] = select ? {
|
|
3876
|
-
select: {
|
|
3877
|
-
...select
|
|
3878
|
-
}
|
|
3879
|
-
} : true;
|
|
3880
|
-
}
|
|
3881
|
-
}
|
|
3882
|
-
}
|
|
3883
|
-
}
|
|
3884
|
-
return {
|
|
3885
|
-
select: result,
|
|
3886
|
-
error: void 0,
|
|
3887
|
-
allIncludes
|
|
3888
|
-
};
|
|
3889
|
-
}
|
|
3890
|
-
makeFilterValue(fieldDef, value, op) {
|
|
3891
|
-
if (fieldDef.relation) {
|
|
3892
|
-
const info = this.getModelInfo(fieldDef.type);
|
|
3893
|
-
if (fieldDef.array) {
|
|
3894
|
-
const values = value.split(",").filter((i) => i);
|
|
3895
|
-
const filterValue = values.length > 1 ? {
|
|
3896
|
-
OR: values.map((v) => this.makeIdFilter(info.idFields, v, false))
|
|
3897
|
-
} : this.makeIdFilter(info.idFields, value, false);
|
|
3898
|
-
return {
|
|
3899
|
-
some: filterValue
|
|
3900
|
-
};
|
|
3901
|
-
} else {
|
|
3902
|
-
const values = value.split(",").filter((i) => i);
|
|
3903
|
-
if (values.length > 1) {
|
|
3904
|
-
return {
|
|
3905
|
-
OR: values.map((v) => this.makeIdFilter(info.idFields, v, false))
|
|
3906
|
-
};
|
|
3907
|
-
} else {
|
|
3908
|
-
return {
|
|
3909
|
-
is: this.makeIdFilter(info.idFields, value, false)
|
|
3910
|
-
};
|
|
3911
|
-
}
|
|
3912
|
-
}
|
|
3913
|
-
} else {
|
|
3914
|
-
if (op === "between") {
|
|
3915
|
-
const parts = value.split(",").map((v) => this.coerce(fieldDef, v));
|
|
3916
|
-
if (parts.length !== 2) {
|
|
3917
|
-
throw new InvalidValueError(`"between" expects exactly 2 comma-separated values`);
|
|
3918
|
-
}
|
|
3919
|
-
return {
|
|
3920
|
-
between: [
|
|
3921
|
-
parts[0],
|
|
3922
|
-
parts[1]
|
|
3923
|
-
]
|
|
3924
|
-
};
|
|
3925
|
-
}
|
|
3926
|
-
const coerced = this.coerce(fieldDef, value);
|
|
3927
|
-
switch (op) {
|
|
3928
|
-
case "icontains":
|
|
3929
|
-
return {
|
|
3930
|
-
contains: coerced,
|
|
3931
|
-
mode: "insensitive"
|
|
3932
|
-
};
|
|
3933
|
-
case "hasSome":
|
|
3934
|
-
case "hasEvery": {
|
|
3935
|
-
const values = value.split(",").filter((i) => i).map((v) => this.coerce(fieldDef, v));
|
|
3936
|
-
return {
|
|
3937
|
-
[op]: values
|
|
3938
|
-
};
|
|
3939
|
-
}
|
|
3940
|
-
case "isEmpty":
|
|
3941
|
-
if (value !== "true" && value !== "false") {
|
|
3942
|
-
throw new InvalidValueError(`Not a boolean: ${value}`);
|
|
3943
|
-
}
|
|
3944
|
-
return {
|
|
3945
|
-
isEmpty: value === "true" ? true : false
|
|
3946
|
-
};
|
|
3947
|
-
default:
|
|
3948
|
-
if (op === void 0) {
|
|
3949
|
-
if (fieldDef.attributes?.some((attr) => attr.name === "@json")) {
|
|
3950
|
-
return {
|
|
3951
|
-
equals: coerced
|
|
3952
|
-
};
|
|
3953
|
-
}
|
|
3954
|
-
const values = value.split(",").filter((i) => i).map((v) => this.coerce(fieldDef, v));
|
|
3955
|
-
return values.length > 1 ? {
|
|
3956
|
-
in: values
|
|
3957
|
-
} : {
|
|
3958
|
-
equals: values[0]
|
|
3959
|
-
};
|
|
3960
|
-
} else {
|
|
3961
|
-
return {
|
|
3962
|
-
[op]: coerced
|
|
3963
|
-
};
|
|
3964
|
-
}
|
|
3965
|
-
}
|
|
3966
|
-
}
|
|
3967
|
-
}
|
|
3968
|
-
injectRelationQuery(type, injectTarget, injectKey, query) {
|
|
3969
|
-
const { filter, error: filterError } = this.buildFilter(type, query);
|
|
3970
|
-
if (filterError) {
|
|
3971
|
-
return filterError;
|
|
3972
|
-
}
|
|
3973
|
-
if (filter) {
|
|
3974
|
-
injectTarget[injectKey] = {
|
|
3975
|
-
...injectTarget[injectKey],
|
|
3976
|
-
where: filter
|
|
3977
|
-
};
|
|
3978
|
-
}
|
|
3979
|
-
const { sort, error: sortError } = this.buildSort(type, query);
|
|
3980
|
-
if (sortError) {
|
|
3981
|
-
return sortError;
|
|
3982
|
-
}
|
|
3983
|
-
if (sort) {
|
|
3984
|
-
injectTarget[injectKey] = {
|
|
3985
|
-
...injectTarget[injectKey],
|
|
3986
|
-
orderBy: sort
|
|
3987
|
-
};
|
|
3988
|
-
}
|
|
3989
|
-
const pagination = this.getPagination(query);
|
|
3990
|
-
const offset = pagination.offset;
|
|
3991
|
-
if (offset > 0) {
|
|
3992
|
-
injectTarget[injectKey] = {
|
|
3993
|
-
...injectTarget[injectKey],
|
|
3994
|
-
skip: offset
|
|
3995
|
-
};
|
|
3996
|
-
}
|
|
3997
|
-
const limit = pagination.limit;
|
|
3998
|
-
if (limit !== Infinity) {
|
|
3999
|
-
injectTarget[injectKey] = {
|
|
4000
|
-
...injectTarget[injectKey],
|
|
4001
|
-
take: limit
|
|
4002
|
-
};
|
|
4003
|
-
injectTarget._count = {
|
|
4004
|
-
select: {
|
|
4005
|
-
[injectKey]: true
|
|
4006
|
-
}
|
|
4007
|
-
};
|
|
4008
|
-
}
|
|
4009
|
-
}
|
|
4010
|
-
handleORMError(err) {
|
|
4011
|
-
return match2(err.reason).with(ORMErrorReason.INVALID_INPUT, () => {
|
|
4012
|
-
return this.makeError("validationError", err.message, 422);
|
|
4013
|
-
}).with(ORMErrorReason.REJECTED_BY_POLICY, () => {
|
|
4014
|
-
return this.makeError("forbidden", err.message, 403, {
|
|
4015
|
-
reason: err.rejectedByPolicyReason
|
|
4016
|
-
});
|
|
4017
|
-
}).with(ORMErrorReason.NOT_FOUND, () => {
|
|
4018
|
-
return this.makeError("notFound", err.message, 404);
|
|
4019
|
-
}).with(ORMErrorReason.DB_QUERY_ERROR, () => {
|
|
4020
|
-
return this.makeError("queryError", err.message, 400, {
|
|
4021
|
-
dbErrorCode: err.dbErrorCode
|
|
4022
|
-
});
|
|
4023
|
-
}).otherwise(() => {
|
|
4024
|
-
return this.makeError("unknownError", err.message);
|
|
4025
|
-
});
|
|
4026
|
-
}
|
|
4027
|
-
makeError(code, detail, status, otherFields = {}) {
|
|
4028
|
-
status = status ?? this.errors[code]?.status ?? 500;
|
|
4029
|
-
const error = {
|
|
4030
|
-
status,
|
|
4031
|
-
code: paramCase(code),
|
|
4032
|
-
title: this.errors[code]?.title
|
|
4033
|
-
};
|
|
4034
|
-
if (detail) {
|
|
4035
|
-
error.detail = detail;
|
|
4036
|
-
}
|
|
4037
|
-
Object.assign(error, otherFields);
|
|
4038
|
-
return {
|
|
4039
|
-
status,
|
|
4040
|
-
body: {
|
|
4041
|
-
errors: [
|
|
4042
|
-
error
|
|
4043
|
-
]
|
|
4044
|
-
}
|
|
4045
|
-
};
|
|
4046
|
-
}
|
|
4047
|
-
makeUnsupportedModelError(model) {
|
|
4048
|
-
return this.makeError("unsupportedModel", `Model ${model} doesn't exist`);
|
|
4049
|
-
}
|
|
4050
|
-
makeUnsupportedRelationshipError(model, relationship, status) {
|
|
4051
|
-
return this.makeError("unsupportedRelationship", `Relationship ${model}.${relationship} doesn't exist`, status);
|
|
4052
|
-
}
|
|
4053
|
-
//#endregion
|
|
4054
|
-
async generateSpec(options) {
|
|
4055
|
-
const generator = new RestApiSpecGenerator(this.options);
|
|
4056
|
-
return generator.generateSpec(options);
|
|
4057
|
-
}
|
|
4058
|
-
};
|
|
4059
|
-
|
|
4060
|
-
// src/api/rpc/index.ts
|
|
4061
|
-
import { lowerCaseFirst as lowerCaseFirst4, safeJSONStringify as safeJSONStringify2 } from "@zenstackhq/common-helpers";
|
|
4062
|
-
import { CoreCrudOperations, ORMError as ORMError3, ORMErrorReason as ORMErrorReason2 } from "@zenstackhq/orm";
|
|
4063
|
-
import SuperJSON4 from "superjson";
|
|
4064
|
-
import { match as match3 } from "ts-pattern";
|
|
4065
|
-
import z3 from "zod";
|
|
4066
|
-
import { fromError as fromError2 } from "zod-validation-error/v4";
|
|
4067
|
-
var TRANSACTION_ROUTE_PREFIX = "$transaction";
|
|
4068
|
-
var VALID_OPS = new Set(CoreCrudOperations);
|
|
4069
|
-
registerCustomSerializers();
|
|
4070
|
-
var RPCApiHandler = class {
|
|
4071
|
-
static {
|
|
4072
|
-
__name(this, "RPCApiHandler");
|
|
4073
|
-
}
|
|
4074
|
-
options;
|
|
4075
|
-
constructor(options) {
|
|
4076
|
-
this.options = options;
|
|
4077
|
-
this.validateOptions(options);
|
|
4078
|
-
}
|
|
4079
|
-
validateOptions(options) {
|
|
4080
|
-
const schema = z3.strictObject({
|
|
4081
|
-
schema: z3.object(),
|
|
4082
|
-
log: loggerSchema.optional(),
|
|
4083
|
-
queryOptions: queryOptionsSchema.optional()
|
|
4084
|
-
});
|
|
4085
|
-
const parseResult = schema.safeParse(options);
|
|
4086
|
-
if (!parseResult.success) {
|
|
4087
|
-
throw new Error(`Invalid options: ${fromError2(parseResult.error)}`);
|
|
4088
|
-
}
|
|
4089
|
-
}
|
|
4090
|
-
get schema() {
|
|
4091
|
-
return this.options.schema;
|
|
4092
|
-
}
|
|
4093
|
-
get log() {
|
|
4094
|
-
return this.options.log;
|
|
4095
|
-
}
|
|
4096
|
-
async handleRequest({ client, method, path, query, requestBody }) {
|
|
4097
|
-
const parts = path.split("/").filter((p) => !!p);
|
|
4098
|
-
const op = parts.pop();
|
|
4099
|
-
let model = parts.pop();
|
|
4100
|
-
if (parts.length !== 0 || !op || !model) {
|
|
4101
|
-
return this.makeBadInputErrorResponse("invalid request path");
|
|
4102
|
-
}
|
|
4103
|
-
if (model === PROCEDURE_ROUTE_PREFIXES) {
|
|
4104
|
-
return this.handleProcedureRequest({
|
|
4105
|
-
client,
|
|
4106
|
-
method: method.toUpperCase(),
|
|
4107
|
-
proc: op,
|
|
4108
|
-
query,
|
|
4109
|
-
requestBody
|
|
4110
|
-
});
|
|
4111
|
-
}
|
|
4112
|
-
if (model === TRANSACTION_ROUTE_PREFIX) {
|
|
4113
|
-
return this.handleTransaction({
|
|
4114
|
-
client,
|
|
4115
|
-
method: method.toUpperCase(),
|
|
4116
|
-
type: op,
|
|
4117
|
-
requestBody
|
|
4118
|
-
});
|
|
4119
|
-
}
|
|
4120
|
-
model = lowerCaseFirst4(model);
|
|
4121
|
-
method = method.toUpperCase();
|
|
4122
|
-
let args;
|
|
4123
|
-
let resCode = 200;
|
|
4124
|
-
switch (op) {
|
|
4125
|
-
case "create":
|
|
4126
|
-
case "createMany":
|
|
4127
|
-
case "createManyAndReturn":
|
|
4128
|
-
case "upsert":
|
|
4129
|
-
if (method !== "POST") {
|
|
4130
|
-
return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
4131
|
-
}
|
|
4132
|
-
if (!requestBody) {
|
|
4133
|
-
return this.makeBadInputErrorResponse("missing request body");
|
|
4134
|
-
}
|
|
4135
|
-
args = requestBody;
|
|
4136
|
-
resCode = 201;
|
|
4137
|
-
break;
|
|
4138
|
-
case "findFirst":
|
|
4139
|
-
case "findUnique":
|
|
4140
|
-
case "findMany":
|
|
4141
|
-
case "aggregate":
|
|
4142
|
-
case "groupBy":
|
|
4143
|
-
case "count":
|
|
4144
|
-
case "exists":
|
|
4145
|
-
if (method !== "GET") {
|
|
4146
|
-
return this.makeBadInputErrorResponse("invalid request method, only GET is supported");
|
|
4147
|
-
}
|
|
4148
|
-
try {
|
|
4149
|
-
args = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : {};
|
|
4150
|
-
} catch {
|
|
4151
|
-
return this.makeBadInputErrorResponse('invalid "q" query parameter');
|
|
4152
|
-
}
|
|
4153
|
-
break;
|
|
4154
|
-
case "update":
|
|
4155
|
-
case "updateMany":
|
|
4156
|
-
case "updateManyAndReturn":
|
|
4157
|
-
if (method !== "PUT" && method !== "PATCH") {
|
|
4158
|
-
return this.makeBadInputErrorResponse("invalid request method, only PUT or PATCH are supported");
|
|
4159
|
-
}
|
|
4160
|
-
if (!requestBody) {
|
|
4161
|
-
return this.makeBadInputErrorResponse("missing request body");
|
|
4162
|
-
}
|
|
4163
|
-
args = requestBody;
|
|
4164
|
-
break;
|
|
4165
|
-
case "delete":
|
|
4166
|
-
case "deleteMany":
|
|
4167
|
-
if (method !== "DELETE") {
|
|
4168
|
-
return this.makeBadInputErrorResponse("invalid request method, only DELETE is supported");
|
|
4169
|
-
}
|
|
4170
|
-
try {
|
|
4171
|
-
args = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : {};
|
|
4172
|
-
} catch (err) {
|
|
4173
|
-
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : 'invalid "q" query parameter');
|
|
4174
|
-
}
|
|
4175
|
-
break;
|
|
4176
|
-
default:
|
|
4177
|
-
return this.makeBadInputErrorResponse("invalid operation: " + op);
|
|
4178
|
-
}
|
|
4179
|
-
const { result: processedArgs, error } = await this.processRequestPayload(args);
|
|
4180
|
-
if (error) {
|
|
4181
|
-
return this.makeBadInputErrorResponse(error);
|
|
4182
|
-
}
|
|
4183
|
-
try {
|
|
4184
|
-
if (!this.isValidModel(client, model)) {
|
|
4185
|
-
return this.makeBadInputErrorResponse(`unknown model name: ${model}`);
|
|
4186
|
-
}
|
|
4187
|
-
log(this.options.log, "debug", () => `handling "${model}.${op}" request with args: ${safeJSONStringify2(processedArgs)}`);
|
|
4188
|
-
const clientResult = await client[model][op](processedArgs);
|
|
4189
|
-
let responseBody = {
|
|
4190
|
-
data: clientResult
|
|
4191
|
-
};
|
|
4192
|
-
if (clientResult) {
|
|
4193
|
-
const { json, meta } = SuperJSON4.serialize(clientResult);
|
|
4194
|
-
responseBody = {
|
|
4195
|
-
data: json
|
|
4196
|
-
};
|
|
4197
|
-
if (meta) {
|
|
4198
|
-
responseBody.meta = {
|
|
4199
|
-
serialization: meta
|
|
4200
|
-
};
|
|
4201
|
-
}
|
|
4202
|
-
}
|
|
4203
|
-
const response = {
|
|
4204
|
-
status: resCode,
|
|
4205
|
-
body: responseBody
|
|
4206
|
-
};
|
|
4207
|
-
log(this.options.log, "debug", () => `sending response for "${model}.${op}" request: ${safeJSONStringify2(response)}`);
|
|
4208
|
-
return response;
|
|
4209
|
-
} catch (err) {
|
|
4210
|
-
log(this.options.log, "error", `error occurred when handling "${model}.${op}" request`, err);
|
|
4211
|
-
if (err instanceof ORMError3) {
|
|
4212
|
-
return this.makeORMErrorResponse(err);
|
|
4213
|
-
} else {
|
|
4214
|
-
return this.makeGenericErrorResponse(err);
|
|
4215
|
-
}
|
|
4216
|
-
}
|
|
4217
|
-
}
|
|
4218
|
-
async handleTransaction({ client, method, type, requestBody }) {
|
|
4219
|
-
if (method !== "POST") {
|
|
4220
|
-
return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
4221
|
-
}
|
|
4222
|
-
if (type !== "sequential") {
|
|
4223
|
-
return this.makeBadInputErrorResponse(`unsupported transaction type: ${type}`);
|
|
4224
|
-
}
|
|
4225
|
-
if (!requestBody || !Array.isArray(requestBody) || requestBody.length === 0) {
|
|
4226
|
-
return this.makeBadInputErrorResponse("request body must be a non-empty array of operations");
|
|
4227
|
-
}
|
|
4228
|
-
const processedOps = [];
|
|
4229
|
-
for (let i = 0; i < requestBody.length; i++) {
|
|
4230
|
-
const item = requestBody[i];
|
|
4231
|
-
if (!item || typeof item !== "object") {
|
|
4232
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} must be an object`);
|
|
4233
|
-
}
|
|
4234
|
-
const { model: itemModel, op: itemOp, args: itemArgs } = item;
|
|
4235
|
-
if (!itemModel || typeof itemModel !== "string") {
|
|
4236
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "model" field`);
|
|
4237
|
-
}
|
|
4238
|
-
if (!itemOp || typeof itemOp !== "string") {
|
|
4239
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} is missing a valid "op" field`);
|
|
4240
|
-
}
|
|
4241
|
-
if (!VALID_OPS.has(itemOp)) {
|
|
4242
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} has invalid op: ${itemOp}`);
|
|
4243
|
-
}
|
|
4244
|
-
if (!this.isValidModel(client, lowerCaseFirst4(itemModel))) {
|
|
4245
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} has unknown model: ${itemModel}`);
|
|
4246
|
-
}
|
|
4247
|
-
if (itemArgs !== void 0 && itemArgs !== null && (typeof itemArgs !== "object" || Array.isArray(itemArgs))) {
|
|
4248
|
-
return this.makeBadInputErrorResponse(`operation at index ${i} has invalid "args" field`);
|
|
4249
|
-
}
|
|
4250
|
-
const { result: processedArgs, error: argsError } = await this.processRequestPayload(itemArgs ?? {});
|
|
4251
|
-
if (argsError) {
|
|
4252
|
-
return this.makeBadInputErrorResponse(`operation at index ${i}: ${argsError}`);
|
|
4253
|
-
}
|
|
4254
|
-
processedOps.push({
|
|
4255
|
-
model: lowerCaseFirst4(itemModel),
|
|
4256
|
-
op: itemOp,
|
|
4257
|
-
args: processedArgs
|
|
4258
|
-
});
|
|
4259
|
-
}
|
|
4260
|
-
try {
|
|
4261
|
-
const promises = processedOps.map(({ model, op, args }) => {
|
|
4262
|
-
return client[model][op](args);
|
|
4263
|
-
});
|
|
4264
|
-
log(this.options.log, "debug", () => `handling "$transaction" request with ${promises.length} operations`);
|
|
4265
|
-
const clientResult = await client.$transaction(promises);
|
|
4266
|
-
const { json, meta } = SuperJSON4.serialize(clientResult);
|
|
4267
|
-
const responseBody = {
|
|
4268
|
-
data: json
|
|
4269
|
-
};
|
|
4270
|
-
if (meta) {
|
|
4271
|
-
responseBody.meta = {
|
|
4272
|
-
serialization: meta
|
|
4273
|
-
};
|
|
4274
|
-
}
|
|
4275
|
-
const response = {
|
|
4276
|
-
status: 200,
|
|
4277
|
-
body: responseBody
|
|
4278
|
-
};
|
|
4279
|
-
log(this.options.log, "debug", () => `sending response for "$transaction" request: ${safeJSONStringify2(response)}`);
|
|
4280
|
-
return response;
|
|
4281
|
-
} catch (err) {
|
|
4282
|
-
log(this.options.log, "error", `error occurred when handling "$transaction" request`, err);
|
|
4283
|
-
if (err instanceof ORMError3) {
|
|
4284
|
-
return this.makeORMErrorResponse(err);
|
|
4285
|
-
}
|
|
4286
|
-
return this.makeGenericErrorResponse(err);
|
|
4287
|
-
}
|
|
4288
|
-
}
|
|
4289
|
-
async handleProcedureRequest({ client, method, proc, query, requestBody }) {
|
|
4290
|
-
if (!proc) {
|
|
4291
|
-
return this.makeBadInputErrorResponse("missing procedure name");
|
|
4292
|
-
}
|
|
4293
|
-
const procDef = getProcedureDef(this.options.schema, proc);
|
|
4294
|
-
if (!procDef) {
|
|
4295
|
-
return this.makeBadInputErrorResponse(`unknown procedure: ${proc}`);
|
|
4296
|
-
}
|
|
4297
|
-
const isMutation = !!procDef.mutation;
|
|
4298
|
-
if (isMutation) {
|
|
4299
|
-
if (method !== "POST") {
|
|
4300
|
-
return this.makeBadInputErrorResponse("invalid request method, only POST is supported");
|
|
4301
|
-
}
|
|
4302
|
-
} else {
|
|
4303
|
-
if (method !== "GET") {
|
|
4304
|
-
return this.makeBadInputErrorResponse("invalid request method, only GET is supported");
|
|
4305
|
-
}
|
|
4306
|
-
}
|
|
4307
|
-
let argsPayload = method === "POST" ? requestBody : void 0;
|
|
4308
|
-
if (method === "GET") {
|
|
4309
|
-
try {
|
|
4310
|
-
argsPayload = query?.["q"] ? unmarshalQ(query["q"], query["meta"]) : void 0;
|
|
4311
|
-
} catch (err) {
|
|
4312
|
-
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : 'invalid "q" query parameter');
|
|
4313
|
-
}
|
|
4314
|
-
}
|
|
4315
|
-
const { result: processedArgsPayload, error } = await processSuperJsonRequestPayload(argsPayload);
|
|
4316
|
-
if (error) {
|
|
4317
|
-
return this.makeBadInputErrorResponse(error);
|
|
4318
|
-
}
|
|
4319
|
-
let procInput;
|
|
4320
|
-
try {
|
|
4321
|
-
procInput = mapProcedureArgs(procDef, processedArgsPayload);
|
|
4322
|
-
} catch (err) {
|
|
4323
|
-
return this.makeBadInputErrorResponse(err instanceof Error ? err.message : "invalid procedure arguments");
|
|
4324
|
-
}
|
|
4325
|
-
try {
|
|
4326
|
-
log(this.options.log, "debug", () => `handling "$procs.${proc}" request`);
|
|
4327
|
-
const clientResult = await client.$procs?.[proc](procInput);
|
|
4328
|
-
const { json, meta } = SuperJSON4.serialize(clientResult);
|
|
4329
|
-
const responseBody = {
|
|
4330
|
-
data: json
|
|
4331
|
-
};
|
|
4332
|
-
if (meta) {
|
|
4333
|
-
responseBody.meta = {
|
|
4334
|
-
serialization: meta
|
|
4335
|
-
};
|
|
4336
|
-
}
|
|
4337
|
-
const response = {
|
|
4338
|
-
status: 200,
|
|
4339
|
-
body: responseBody
|
|
4340
|
-
};
|
|
4341
|
-
log(this.options.log, "debug", () => `sending response for "$procs.${proc}" request: ${safeJSONStringify2(response)}`);
|
|
4342
|
-
return response;
|
|
4343
|
-
} catch (err) {
|
|
4344
|
-
log(this.options.log, "error", `error occurred when handling "$procs.${proc}" request`, err);
|
|
4345
|
-
if (err instanceof ORMError3) {
|
|
4346
|
-
return this.makeORMErrorResponse(err);
|
|
4347
|
-
}
|
|
4348
|
-
return this.makeGenericErrorResponse(err);
|
|
4349
|
-
}
|
|
4350
|
-
}
|
|
4351
|
-
isValidModel(client, model) {
|
|
4352
|
-
return Object.keys(client.$schema.models).some((m) => lowerCaseFirst4(m) === lowerCaseFirst4(model));
|
|
4353
|
-
}
|
|
4354
|
-
makeBadInputErrorResponse(message) {
|
|
4355
|
-
const resp = {
|
|
4356
|
-
status: 400,
|
|
4357
|
-
body: {
|
|
4358
|
-
error: {
|
|
4359
|
-
message
|
|
4360
|
-
}
|
|
4361
|
-
}
|
|
4362
|
-
};
|
|
4363
|
-
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify2(resp)}`);
|
|
4364
|
-
return resp;
|
|
4365
|
-
}
|
|
4366
|
-
makeGenericErrorResponse(err) {
|
|
4367
|
-
const resp = {
|
|
4368
|
-
status: 500,
|
|
4369
|
-
body: {
|
|
4370
|
-
error: {
|
|
4371
|
-
message: err instanceof Error ? err.message : "unknown error"
|
|
4372
|
-
}
|
|
4373
|
-
}
|
|
4374
|
-
};
|
|
4375
|
-
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify2(resp)}${err instanceof Error ? "\n" + err.stack : ""}`);
|
|
4376
|
-
return resp;
|
|
4377
|
-
}
|
|
4378
|
-
makeORMErrorResponse(err) {
|
|
4379
|
-
let status = 400;
|
|
4380
|
-
const error = {
|
|
4381
|
-
message: err.message,
|
|
4382
|
-
reason: err.reason
|
|
4383
|
-
};
|
|
4384
|
-
match3(err.reason).with(ORMErrorReason2.NOT_FOUND, () => {
|
|
4385
|
-
status = 404;
|
|
4386
|
-
error.model = err.model;
|
|
4387
|
-
}).with(ORMErrorReason2.INVALID_INPUT, () => {
|
|
4388
|
-
status = 422;
|
|
4389
|
-
error.rejectedByValidation = true;
|
|
4390
|
-
error.model = err.model;
|
|
4391
|
-
}).with(ORMErrorReason2.REJECTED_BY_POLICY, () => {
|
|
4392
|
-
status = 403;
|
|
4393
|
-
error.rejectedByPolicy = true;
|
|
4394
|
-
error.model = err.model;
|
|
4395
|
-
error.rejectReason = err.rejectedByPolicyReason;
|
|
4396
|
-
}).with(ORMErrorReason2.DB_QUERY_ERROR, () => {
|
|
4397
|
-
status = 400;
|
|
4398
|
-
error.dbErrorCode = err.dbErrorCode;
|
|
4399
|
-
}).otherwise(() => {
|
|
4400
|
-
});
|
|
4401
|
-
const resp = {
|
|
4402
|
-
status,
|
|
4403
|
-
body: {
|
|
4404
|
-
error
|
|
4405
|
-
}
|
|
4406
|
-
};
|
|
4407
|
-
log(this.options.log, "debug", () => `sending error response: ${safeJSONStringify2(resp)}`);
|
|
4408
|
-
return resp;
|
|
4409
|
-
}
|
|
4410
|
-
async processRequestPayload(args) {
|
|
4411
|
-
const { meta, ...rest } = args ?? {};
|
|
4412
|
-
if (meta?.serialization) {
|
|
4413
|
-
try {
|
|
4414
|
-
args = SuperJSON4.deserialize({
|
|
4415
|
-
json: rest,
|
|
4416
|
-
meta: meta.serialization
|
|
4417
|
-
});
|
|
4418
|
-
} catch (err) {
|
|
4419
|
-
return {
|
|
4420
|
-
result: void 0,
|
|
4421
|
-
error: `failed to deserialize request payload: ${err.message}`
|
|
4422
|
-
};
|
|
4423
|
-
}
|
|
4424
|
-
} else {
|
|
4425
|
-
args = rest;
|
|
4426
|
-
}
|
|
4427
|
-
return {
|
|
4428
|
-
result: args,
|
|
4429
|
-
error: void 0
|
|
4430
|
-
};
|
|
4431
|
-
}
|
|
4432
|
-
};
|
|
4433
|
-
export {
|
|
4434
|
-
RPCApiHandler,
|
|
4435
|
-
RestApiHandler
|
|
4436
|
-
};
|
|
4437
|
-
//# sourceMappingURL=api.js.map
|