@jskit-ai/crud-core 0.2.2 → 0.2.4
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/locales/en.json +2 -1
- package/package.json +7 -7
- package/patterns/json-api-resource-package/PATTERN.md +102 -23
- package/patterns/json-api-resource-package/example/packages/books/package.json +3 -2
- package/patterns/json-api-resource-package/example/packages/books/src/server/types.js +5 -0
- package/src/server/createCrudServiceFromResource.js +14 -6
- package/src/server/createHooksToCollectChildren.js +123 -97
- package/src/server/defineCrudJsonApiFeature.js +40 -8
- package/src/server/fieldAccess.js +33 -25
- package/src/server/jsonApiModule/actions.js +151 -548
- package/src/server/jsonApiModule/assistantExtension.js +386 -0
- package/src/server/jsonApiModule/customActionId.js +12 -0
- package/src/server/jsonApiModule/repository.js +73 -21
- package/src/server/jsonApiModule/routes.js +44 -30
- package/src/server/jsonApiModule/service.js +37 -35
- package/src/server/jsonApiResourceContract.js +22 -18
- package/src/server/listFilterJsonRest.js +304 -0
- package/src/server/listFilterTypes.js +427 -0
- package/src/server/listFilters.js +26 -722
- package/src/server/listQueryValidators.js +26 -21
- package/src/server/lookupPathSupport.js +31 -18
- package/src/server/lookups.js +20 -34
- package/src/server/normalizeOptionalText.js +13 -0
- package/src/server/repositorySupport.js +11 -10
- package/src/server/resourceRuntime/compiledRuntime.js +284 -0
- package/src/server/resourceRuntime/index.js +167 -920
- package/src/server/resourceRuntime/listControls.js +333 -0
- package/src/server/resourceRuntime/lookupHydration.js +121 -186
- package/src/server/resourceRuntime/operationStages.js +140 -0
- package/src/server/resourceRuntime/recordValidation.js +65 -0
- package/src/server/routeContracts.js +44 -46
- package/src/server/serviceEvents.js +42 -118
- package/src/server/serviceMethods.js +34 -26
- package/src/server/types.js +156 -0
- package/test/assistantActionConformance.test.js +8 -5
- package/test/assistantPagination.integration.test.js +5 -3
- package/test/createCrudServiceFromResource.test.js +0 -18
- package/test/customActionId.test.js +12 -0
- package/test/defineCrudJsonApiFeature.test.js +193 -28
- package/test/errorCodes.test.js +18 -0
- package/test/jsonApiRepository.test.js +103 -3
- package/test/listFilters.test.js +7 -7
- package/test/listQueryValidators.test.js +1 -54
- package/test/serviceEvents.test.js +31 -81
- package/test/support/crudJsonApiActionOptions.js +37 -0
- package/src/server/crudModuleConfig.js +0 -181
- package/src/server/lookupHydration.js +0 -710
- package/test/crudModuleConfig.test.js +0 -33
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { createSchema } from "@jskit-ai/kernel/shared/validators";
|
|
2
|
+
import { normalizeJsonApiFieldsets } from "@jskit-ai/kernel/shared/support/jsonApiFieldsets";
|
|
3
|
+
import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
4
|
+
import {
|
|
5
|
+
decodeJsonApiResourceResponse,
|
|
6
|
+
jsonApiResultValue,
|
|
7
|
+
normalizeJsonApiDocument
|
|
8
|
+
} from "@jskit-ai/http-runtime/shared";
|
|
9
|
+
import {
|
|
10
|
+
resolveDeclaredLookupContainerKey,
|
|
11
|
+
resolveJsonApiFieldsetContract,
|
|
12
|
+
resolveJsonApiRelationshipEntries,
|
|
13
|
+
resolveSchemaFieldDefinitions
|
|
14
|
+
} from "../jsonApiResourceContract.js";
|
|
15
|
+
import { normalizeOptionalText } from "../normalizeOptionalText.js";
|
|
16
|
+
|
|
17
|
+
const CRUD_ASSISTANT_RESOURCE_OPERATION = Object.freeze({
|
|
18
|
+
list: "list",
|
|
19
|
+
view: "view",
|
|
20
|
+
create: "create",
|
|
21
|
+
update: "patch",
|
|
22
|
+
delete: "delete"
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
function resolveAssistantResultValue(result) {
|
|
26
|
+
const value = jsonApiResultValue(result);
|
|
27
|
+
const document = normalizeJsonApiDocument(value);
|
|
28
|
+
return {
|
|
29
|
+
value,
|
|
30
|
+
document
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function buildProjectionRecordSchema(recordSchema, {
|
|
35
|
+
lookupContainerKey = "",
|
|
36
|
+
relationshipEntries = []
|
|
37
|
+
} = {}) {
|
|
38
|
+
// readable-check: allow optional-call - data: a resource's output schema without field definitions passes through
|
|
39
|
+
const definitions = recordSchema?.getFieldDefinitions?.();
|
|
40
|
+
if (!isRecord(definitions)) {
|
|
41
|
+
return recordSchema;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const fields = Object.fromEntries(
|
|
45
|
+
Object.entries(definitions).map(([fieldKey, fieldDefinition]) => [
|
|
46
|
+
fieldKey,
|
|
47
|
+
{
|
|
48
|
+
...fieldDefinition,
|
|
49
|
+
required: fieldKey === "id" && fieldDefinition?.required === true
|
|
50
|
+
}
|
|
51
|
+
])
|
|
52
|
+
);
|
|
53
|
+
if (lookupContainerKey && isRecord(fields[lookupContainerKey])) {
|
|
54
|
+
const createRelatedRecordSchema = (entry) => createSchema({
|
|
55
|
+
id: {
|
|
56
|
+
type: "string",
|
|
57
|
+
required: true
|
|
58
|
+
},
|
|
59
|
+
...(entry.labelKey && entry.labelKey !== "id"
|
|
60
|
+
? {
|
|
61
|
+
[entry.labelKey]: {
|
|
62
|
+
type: "string",
|
|
63
|
+
required: false,
|
|
64
|
+
nullable: true
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
: {})
|
|
68
|
+
});
|
|
69
|
+
const lookupFields = Object.fromEntries(
|
|
70
|
+
relationshipEntries.map((entry) => [
|
|
71
|
+
entry.relationshipName,
|
|
72
|
+
entry.many === true
|
|
73
|
+
? {
|
|
74
|
+
type: "array",
|
|
75
|
+
required: false,
|
|
76
|
+
items: {
|
|
77
|
+
type: "object",
|
|
78
|
+
schema: createRelatedRecordSchema(entry),
|
|
79
|
+
additionalProperties: true
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
: {
|
|
83
|
+
type: "object",
|
|
84
|
+
required: false,
|
|
85
|
+
schema: createRelatedRecordSchema(entry),
|
|
86
|
+
additionalProperties: true
|
|
87
|
+
}
|
|
88
|
+
])
|
|
89
|
+
);
|
|
90
|
+
fields[lookupContainerKey] = {
|
|
91
|
+
...fields[lookupContainerKey],
|
|
92
|
+
type: "object",
|
|
93
|
+
required: false,
|
|
94
|
+
...(Object.keys(lookupFields).length > 0 ? { schema: createSchema(lookupFields) } : {}),
|
|
95
|
+
additionalProperties: true
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return createSchema(fields);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function buildProjectionOutputDefinition(output, operation, relationshipEntries, lookupContainerKey) {
|
|
103
|
+
if (!output || (operation !== "list" && operation !== "view")) {
|
|
104
|
+
return output;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (operation === "view") {
|
|
108
|
+
return Object.freeze({
|
|
109
|
+
schema: buildProjectionRecordSchema(output.schema, { lookupContainerKey, relationshipEntries }),
|
|
110
|
+
mode: "replace"
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const listFields = resolveSchemaFieldDefinitions(output);
|
|
115
|
+
const items = listFields.items;
|
|
116
|
+
// readable-check: allow method-probe - data: a resource's output schema without field definitions passes through
|
|
117
|
+
if (!isRecord(items) || items.type !== "array" || typeof items.items?.getFieldDefinitions !== "function") {
|
|
118
|
+
return output;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return Object.freeze({
|
|
122
|
+
schema: createSchema({
|
|
123
|
+
...listFields,
|
|
124
|
+
items: {
|
|
125
|
+
...items,
|
|
126
|
+
items: buildProjectionRecordSchema(items.items, { lookupContainerKey, relationshipEntries })
|
|
127
|
+
}
|
|
128
|
+
}),
|
|
129
|
+
mode: "replace"
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function buildCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey) {
|
|
134
|
+
const lookupFieldMap = Object.fromEntries(
|
|
135
|
+
relationshipEntries
|
|
136
|
+
.filter((entry) => entry.many !== true)
|
|
137
|
+
.map((entry) => [entry.relationshipName, entry.attributeKey])
|
|
138
|
+
);
|
|
139
|
+
return Object.freeze({
|
|
140
|
+
kind: "jsonapi-resource",
|
|
141
|
+
responseType: resource.namespace,
|
|
142
|
+
responseKind: operation === "list" ? "collection" : "record",
|
|
143
|
+
...(lookupContainerKey ? { lookupContainerKey } : {}),
|
|
144
|
+
...(Object.keys(lookupFieldMap).length > 0 ? { lookupFieldMap } : {})
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function projectCrudAssistantRecordFields(record, selectedFields = null, {
|
|
149
|
+
preserveKeys = []
|
|
150
|
+
} = {}) {
|
|
151
|
+
if (!isRecord(record) || !Array.isArray(selectedFields)) {
|
|
152
|
+
return record;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const allowedKeys = new Set(["id", ...preserveKeys, ...selectedFields]);
|
|
156
|
+
return Object.fromEntries(
|
|
157
|
+
Object.entries(record).filter(([key]) => allowedKeys.has(key))
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function projectCrudAssistantLookupValue(value, selectedFields = null) {
|
|
162
|
+
if (Array.isArray(value)) {
|
|
163
|
+
return value.map((entry) => projectCrudAssistantRecordFields(entry, selectedFields));
|
|
164
|
+
}
|
|
165
|
+
return projectCrudAssistantRecordFields(value, selectedFields);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function projectCrudAssistantReadRecord(record, {
|
|
169
|
+
lookupContainerKey = "",
|
|
170
|
+
primaryFields = null,
|
|
171
|
+
relatedFieldsByLookupKey = new Map()
|
|
172
|
+
} = {}) {
|
|
173
|
+
if (!isRecord(record)) {
|
|
174
|
+
return record;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const primaryProjection = projectCrudAssistantRecordFields(record, primaryFields, {
|
|
178
|
+
preserveKeys: lookupContainerKey && isRecord(record[lookupContainerKey])
|
|
179
|
+
? [lookupContainerKey]
|
|
180
|
+
: []
|
|
181
|
+
});
|
|
182
|
+
const projectedRecord = primaryProjection === record ? { ...record } : primaryProjection;
|
|
183
|
+
if (!lookupContainerKey || !isRecord(projectedRecord[lookupContainerKey])) {
|
|
184
|
+
return projectedRecord;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
projectedRecord[lookupContainerKey] = Object.fromEntries(
|
|
188
|
+
Object.entries(projectedRecord[lookupContainerKey]).map(([lookupKey, value]) => {
|
|
189
|
+
return [
|
|
190
|
+
lookupKey,
|
|
191
|
+
projectCrudAssistantLookupValue(value, relatedFieldsByLookupKey.get(lookupKey))
|
|
192
|
+
];
|
|
193
|
+
})
|
|
194
|
+
);
|
|
195
|
+
return projectedRecord;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function buildCrudAssistantResultProjection(input, resource, relationshipEntries = []) {
|
|
199
|
+
const primaryType = normalizeText(resource.namespace);
|
|
200
|
+
const fieldsets = normalizeJsonApiFieldsets(input.fields, {
|
|
201
|
+
primaryType
|
|
202
|
+
});
|
|
203
|
+
if (Object.keys(fieldsets).length < 1) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const relatedFieldsByLookupKey = new Map();
|
|
208
|
+
for (const entry of relationshipEntries) {
|
|
209
|
+
const selectedFields = fieldsets[entry.relationshipType];
|
|
210
|
+
if (!Array.isArray(selectedFields)) {
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
relatedFieldsByLookupKey.set(entry.relationshipName, selectedFields);
|
|
214
|
+
relatedFieldsByLookupKey.set(entry.attributeKey, selectedFields);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return {
|
|
218
|
+
primaryFields: fieldsets[primaryType],
|
|
219
|
+
relatedFieldsByLookupKey
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function projectCrudAssistantReadResult(result, projection = null, {
|
|
224
|
+
lookupContainerKey = ""
|
|
225
|
+
} = {}) {
|
|
226
|
+
if (!projection) {
|
|
227
|
+
return result;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const projectionOptions = {
|
|
231
|
+
...projection,
|
|
232
|
+
lookupContainerKey
|
|
233
|
+
};
|
|
234
|
+
if (isRecord(result) && Array.isArray(result.items)) {
|
|
235
|
+
return {
|
|
236
|
+
...result,
|
|
237
|
+
items: result.items.map((entry) => projectCrudAssistantReadRecord(entry, projectionOptions))
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return projectCrudAssistantReadRecord(result, projectionOptions);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function transformCrudAssistantResult(operation, result, {
|
|
245
|
+
input = {},
|
|
246
|
+
resource,
|
|
247
|
+
relationshipEntries = [],
|
|
248
|
+
lookupContainerKey = ""
|
|
249
|
+
} = {}) {
|
|
250
|
+
if (operation === "delete") {
|
|
251
|
+
return {
|
|
252
|
+
id: String(input.recordId || ""),
|
|
253
|
+
deleted: true
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const resolved = resolveAssistantResultValue(result);
|
|
258
|
+
const projection = operation === "list" || operation === "view"
|
|
259
|
+
? buildCrudAssistantResultProjection(input, resource, relationshipEntries)
|
|
260
|
+
: null;
|
|
261
|
+
const projectReadResult = (value) => projectCrudAssistantReadResult(value, projection, {
|
|
262
|
+
lookupContainerKey
|
|
263
|
+
});
|
|
264
|
+
if (operation === "list") {
|
|
265
|
+
if (resolved.document.kind === "collection") {
|
|
266
|
+
const decoded = decodeJsonApiResourceResponse(
|
|
267
|
+
resolved.value,
|
|
268
|
+
buildCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey)
|
|
269
|
+
);
|
|
270
|
+
return projectReadResult({
|
|
271
|
+
items: decoded.items,
|
|
272
|
+
nextCursor: normalizeOptionalText(decoded.nextCursor)
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (Array.isArray(resolved.value)) {
|
|
276
|
+
return projectReadResult({
|
|
277
|
+
items: resolved.value,
|
|
278
|
+
nextCursor: null
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
if (isRecord(resolved.value) && Array.isArray(resolved.value.items)) {
|
|
282
|
+
return projectReadResult({
|
|
283
|
+
items: resolved.value.items,
|
|
284
|
+
nextCursor: normalizeOptionalText(resolved.value.nextCursor)
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
return resolved.value;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (resolved.document.kind === "resource") {
|
|
291
|
+
return projectReadResult(decodeJsonApiResourceResponse(
|
|
292
|
+
resolved.value,
|
|
293
|
+
buildCrudAssistantTransport(resource, operation, relationshipEntries, lookupContainerKey)
|
|
294
|
+
));
|
|
295
|
+
}
|
|
296
|
+
return projectReadResult(resolved.value);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function buildCrudAssistantReadDescription({
|
|
300
|
+
fieldsetContract,
|
|
301
|
+
lookupContainerKey = "",
|
|
302
|
+
namespace = "",
|
|
303
|
+
operation = "list"
|
|
304
|
+
} = {}) {
|
|
305
|
+
const relationshipEntries = fieldsetContract.relationshipEntries;
|
|
306
|
+
const firstRelationship = relationshipEntries[0] || null;
|
|
307
|
+
const includeExample = relationshipEntries.length > 0
|
|
308
|
+
? relationshipEntries.slice(0, 2).map((entry) => entry.relationshipName).join(",")
|
|
309
|
+
: "author,publisher";
|
|
310
|
+
const fieldsExample = firstRelationship
|
|
311
|
+
? ` fields can be {\"${namespace}\":[\"${firstRelationship.attributeKey}\"],` +
|
|
312
|
+
`\"${firstRelationship.relationshipType}\":[\"${firstRelationship.labelKey || "id"}\"]}.`
|
|
313
|
+
: ` fields can be {\"${namespace}\":[\"id\"]}.`;
|
|
314
|
+
const aliasGuidance = fieldsetContract.aliasMappings
|
|
315
|
+
.map((entry) => `use \"${entry.resourceType}\" instead of \"${entry.alias}\"`)
|
|
316
|
+
.join("; ");
|
|
317
|
+
const fieldsetKeyGuidance = fieldsetContract.resourceTypes.length > 0
|
|
318
|
+
? ` fields keys must be JSON:API resource types: ${fieldsetContract.resourceTypes.map((entry) => `\"${entry}\"`).join(", ")}.` +
|
|
319
|
+
(aliasGuidance ? ` Relationship aliases are invalid fieldset keys; ${aliasGuidance}.` : "")
|
|
320
|
+
: "";
|
|
321
|
+
const primaryFieldGuidance = fieldsetContract.primaryFields.length > 0
|
|
322
|
+
? ` Valid \"${namespace}\" fields: ${fieldsetContract.primaryFields.map((entry) => `\"${entry}\"`).join(", ")}.`
|
|
323
|
+
: "";
|
|
324
|
+
const relationshipGuidance = relationshipEntries.length > 0
|
|
325
|
+
? ` Include relationships: ${relationshipEntries.map((entry) => {
|
|
326
|
+
const lookupPath = lookupContainerKey
|
|
327
|
+
? ` -> ${operation === "list" ? "items[]." : ""}${lookupContainerKey}.${entry.relationshipName}`
|
|
328
|
+
: "";
|
|
329
|
+
return `\"${entry.relationshipName}\" -> resource type \"${entry.relationshipType}\"${lookupPath}`;
|
|
330
|
+
}).join("; ")}.`
|
|
331
|
+
: "";
|
|
332
|
+
|
|
333
|
+
const subject = operation === "list" ? `List ${namespace} records.` : `View a ${namespace} record.`;
|
|
334
|
+
return `${subject} include must be a comma-separated string such as \"${includeExample}\";` +
|
|
335
|
+
`${fieldsExample}${fieldsetKeyGuidance}${primaryFieldGuidance}${relationshipGuidance}`;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function createCrudAssistantExtension(resource, namespace, operation) {
|
|
339
|
+
const resourceOperation = CRUD_ASSISTANT_RESOURCE_OPERATION[operation];
|
|
340
|
+
const nativeOutput = resource?.operations?.[resourceOperation]?.output || null;
|
|
341
|
+
const recordOutput = operation === "list"
|
|
342
|
+
? Object.freeze({
|
|
343
|
+
schema: resolveSchemaFieldDefinitions(nativeOutput).items?.items,
|
|
344
|
+
mode: "replace"
|
|
345
|
+
})
|
|
346
|
+
: nativeOutput;
|
|
347
|
+
const relationshipEntries = resolveJsonApiRelationshipEntries(recordOutput);
|
|
348
|
+
const lookupContainerKey = resolveDeclaredLookupContainerKey(resource);
|
|
349
|
+
const output = buildProjectionOutputDefinition(
|
|
350
|
+
nativeOutput,
|
|
351
|
+
operation,
|
|
352
|
+
relationshipEntries,
|
|
353
|
+
lookupContainerKey
|
|
354
|
+
);
|
|
355
|
+
const actionLabel = operation === "list" || operation === "view"
|
|
356
|
+
? buildCrudAssistantReadDescription({
|
|
357
|
+
fieldsetContract: resolveJsonApiFieldsetContract(resource),
|
|
358
|
+
lookupContainerKey,
|
|
359
|
+
namespace,
|
|
360
|
+
operation
|
|
361
|
+
})
|
|
362
|
+
: operation === "create"
|
|
363
|
+
? `Create a ${namespace} record.`
|
|
364
|
+
: operation === "update"
|
|
365
|
+
? `Update a ${namespace} record.`
|
|
366
|
+
: `Delete a ${namespace} record.`;
|
|
367
|
+
|
|
368
|
+
function transformResult(result, context) {
|
|
369
|
+
return transformCrudAssistantResult(operation, result, {
|
|
370
|
+
...context,
|
|
371
|
+
resource,
|
|
372
|
+
relationshipEntries,
|
|
373
|
+
lookupContainerKey
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
return Object.freeze({
|
|
378
|
+
description: actionLabel,
|
|
379
|
+
output,
|
|
380
|
+
transformResult
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
export {
|
|
385
|
+
createCrudAssistantExtension
|
|
386
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The action id of a CRUD custom action: its definition's explicit `id`, else `crud.<namespace>.<name>`, the prefix
|
|
3
|
+
* the built-in operations' ids have too. The actions and the routes of a CRUD feature both read it here.
|
|
4
|
+
* @param {string} namespace
|
|
5
|
+
* @param {string} name
|
|
6
|
+
* @param {{ id?: string }} definition
|
|
7
|
+
*/
|
|
8
|
+
function buildCrudCustomActionId(namespace, name, definition) {
|
|
9
|
+
return String(definition.id || `crud.${namespace}.${name}`).trim();
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export { buildCrudCustomActionId };
|
|
@@ -4,12 +4,16 @@ import {
|
|
|
4
4
|
returnBadRequestWhenJsonRestFieldsetInvalid,
|
|
5
5
|
returnNullWhenJsonRestResourceMissing
|
|
6
6
|
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
7
|
-
import { retryDeadlocks } from "@jskit-ai/database-runtime/shared";
|
|
7
|
+
import { resolveTransaction, retryDeadlocks } from "@jskit-ai/database-runtime/shared";
|
|
8
|
+
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
8
9
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
10
|
+
/**
|
|
11
|
+
* @param {object} dependencies
|
|
12
|
+
* @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} dependencies.api
|
|
13
|
+
* @param {import("../types.js").CrudResourceDefinition} dependencies.resource
|
|
14
|
+
* @param {string} dependencies.resourceScopeName
|
|
15
|
+
*/
|
|
16
|
+
function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
13
17
|
if (!resource || typeof resource !== "object" || Array.isArray(resource)) {
|
|
14
18
|
throw new TypeError("createCrudJsonApiRepository requires resource.");
|
|
15
19
|
}
|
|
@@ -24,7 +28,7 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
24
28
|
|
|
25
29
|
// A write given no transaction owns one, so it is outermost and may re-run.
|
|
26
30
|
function write(options, run) {
|
|
27
|
-
return options
|
|
31
|
+
return resolveTransaction(options) ? run() : retryDeadlocks(run);
|
|
28
32
|
}
|
|
29
33
|
|
|
30
34
|
function inputData(payload) {
|
|
@@ -49,7 +53,7 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
49
53
|
}
|
|
50
54
|
|
|
51
55
|
function requireApiResource() {
|
|
52
|
-
const apiResource = api.resources
|
|
56
|
+
const apiResource = api.resources[scopeName];
|
|
53
57
|
if (!apiResource) {
|
|
54
58
|
throw new Error(`JSON REST resource "${scopeName}" is not registered.`);
|
|
55
59
|
}
|
|
@@ -61,10 +65,10 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
61
65
|
requireApiResource().query(
|
|
62
66
|
{
|
|
63
67
|
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
64
|
-
transaction: options
|
|
68
|
+
transaction: resolveTransaction(options),
|
|
65
69
|
format: "jsonapi"
|
|
66
70
|
},
|
|
67
|
-
createJsonRestContext(options.context
|
|
71
|
+
createJsonRestContext(options.context)
|
|
68
72
|
)
|
|
69
73
|
);
|
|
70
74
|
}
|
|
@@ -76,10 +80,10 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
76
80
|
{
|
|
77
81
|
id: recordId,
|
|
78
82
|
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
79
|
-
transaction: options
|
|
83
|
+
transaction: resolveTransaction(options),
|
|
80
84
|
format: "jsonapi"
|
|
81
85
|
},
|
|
82
|
-
createJsonRestContext(options.context
|
|
86
|
+
createJsonRestContext(options.context)
|
|
83
87
|
)
|
|
84
88
|
)
|
|
85
89
|
);
|
|
@@ -90,16 +94,15 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
90
94
|
{
|
|
91
95
|
data: inputData(payload),
|
|
92
96
|
returning: "full",
|
|
93
|
-
transaction: options
|
|
97
|
+
transaction: resolveTransaction(options),
|
|
94
98
|
format: "jsonapi"
|
|
95
99
|
},
|
|
96
|
-
createJsonRestContext(options.context
|
|
100
|
+
createJsonRestContext(options.context)
|
|
97
101
|
));
|
|
98
102
|
}
|
|
99
103
|
|
|
100
|
-
async function patchDocumentById(recordId, patch
|
|
101
|
-
|
|
102
|
-
if (Object.keys(sourcePatch).length < 1) {
|
|
104
|
+
async function patchDocumentById(recordId, patch, options = {}) {
|
|
105
|
+
if (Object.keys(patch).length < 1) {
|
|
103
106
|
return getDocumentById(recordId, {}, options);
|
|
104
107
|
}
|
|
105
108
|
|
|
@@ -107,26 +110,74 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
107
110
|
requireApiResource().patch(
|
|
108
111
|
{
|
|
109
112
|
id: recordId,
|
|
110
|
-
data: inputData(
|
|
113
|
+
data: inputData(patch),
|
|
111
114
|
returning: "full",
|
|
112
|
-
transaction: options
|
|
115
|
+
transaction: resolveTransaction(options),
|
|
113
116
|
format: "jsonapi"
|
|
114
117
|
},
|
|
115
|
-
createJsonRestContext(options.context
|
|
118
|
+
createJsonRestContext(options.context)
|
|
116
119
|
)
|
|
117
120
|
));
|
|
118
121
|
}
|
|
119
122
|
|
|
123
|
+
/**
|
|
124
|
+
* Patches a record only while its lockVersionField still holds
|
|
125
|
+
* expectedLockVersion, and adds one to it in the same transaction: the
|
|
126
|
+
* caller's `trx`, or one it owns. Returns the patched document, or null when
|
|
127
|
+
* the record does not exist or is out of the caller's scope; a record whose
|
|
128
|
+
* lock version has moved on rejects with a 409 `crud.document.lockVersionConflict`.
|
|
129
|
+
* @param {string | number} recordId
|
|
130
|
+
* @param {number} expectedLockVersion
|
|
131
|
+
* @param {Record<string, unknown>} patch
|
|
132
|
+
* @param {{ trx?: any, context?: object }} [options]
|
|
133
|
+
*/
|
|
134
|
+
async function patchDocumentIfLockVersion(recordId, expectedLockVersion, patch, options = {}) {
|
|
135
|
+
const lockVersionField = resource.lockVersionField;
|
|
136
|
+
if (!lockVersionField) {
|
|
137
|
+
throw new TypeError(`patchDocumentIfLockVersion needs resource "${scopeName}" to name its lockVersionField.`);
|
|
138
|
+
}
|
|
139
|
+
if (!Number.isSafeInteger(expectedLockVersion) || expectedLockVersion < 0) {
|
|
140
|
+
throw new TypeError(`patchDocumentIfLockVersion expectedLockVersion must be a non-negative integer. Received: ${expectedLockVersion}`);
|
|
141
|
+
}
|
|
142
|
+
if (Object.hasOwn(patch, lockVersionField)) {
|
|
143
|
+
throw new TypeError(`patchDocumentIfLockVersion advances ${lockVersionField} itself, so the patch must leave it out.`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function patchAtLockVersion(trx) {
|
|
147
|
+
const scoped = { ...options, trx };
|
|
148
|
+
if (!await getDocumentById(recordId, {}, scoped)) {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
const storage = api.knex.helpers.getStorageAdapter(scopeName);
|
|
152
|
+
const lockColumn = storage.translateColumn(lockVersionField);
|
|
153
|
+
const claimed = await storage.buildBaseQuery({ transaction: trx })
|
|
154
|
+
.where(storage.getIdColumn(), storage.translateFilterValue("id", recordId))
|
|
155
|
+
.where(lockColumn, expectedLockVersion)
|
|
156
|
+
.update({ [lockColumn]: expectedLockVersion + 1 });
|
|
157
|
+
if (claimed < 1) {
|
|
158
|
+
throw new AppError(409, "This record changed. Reload and try again.", {
|
|
159
|
+
code: "crud.document.lockVersionConflict"
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
return patchDocumentById(recordId, patch, scoped);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const trx = resolveTransaction(options);
|
|
166
|
+
return trx
|
|
167
|
+
? patchAtLockVersion(trx)
|
|
168
|
+
: returnNullWhenJsonRestResourceMissing(() => withTransaction(patchAtLockVersion));
|
|
169
|
+
}
|
|
170
|
+
|
|
120
171
|
async function deleteDocumentById(recordId, options = {}) {
|
|
121
172
|
return returnNullWhenJsonRestResourceMissing(async () => {
|
|
122
173
|
await write(options, () => requireApiResource().delete(
|
|
123
174
|
{
|
|
124
175
|
id: recordId,
|
|
125
176
|
returning: "none",
|
|
126
|
-
transaction: options
|
|
177
|
+
transaction: resolveTransaction(options),
|
|
127
178
|
format: "jsonapi"
|
|
128
179
|
},
|
|
129
|
-
createJsonRestContext(options.context
|
|
180
|
+
createJsonRestContext(options.context)
|
|
130
181
|
));
|
|
131
182
|
return null;
|
|
132
183
|
});
|
|
@@ -138,6 +189,7 @@ function createCrudJsonApiRepository({ api, resource, resourceScopeName } = {})
|
|
|
138
189
|
getDocumentById,
|
|
139
190
|
createDocument,
|
|
140
191
|
patchDocumentById,
|
|
192
|
+
patchDocumentIfLockVersion,
|
|
141
193
|
deleteDocumentById
|
|
142
194
|
});
|
|
143
195
|
}
|