@jskit-ai/crud-core 0.2.13 → 0.2.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -0
- package/locales/en.json +1 -11
- package/package.json +19 -19
- package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
- package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
- package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
- package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
- package/src/server/createHooksToCollectChildren.js +56 -34
- package/src/server/crudContracts.js +54 -0
- package/src/server/defineCrudFeature.js +509 -0
- package/src/server/jsonApiModule/actions.js +44 -30
- package/src/server/jsonApiModule/routes.js +2 -2
- package/src/server/jsonApiModule/service.js +213 -32
- package/src/server/jsonApiResourceContract.js +41 -1
- package/src/server/listQueryValidators.js +1 -1
- package/src/server/removedApi.js +87 -0
- package/src/server/types.js +26 -50
- package/test/assistantActionConformance.test.js +20 -21
- package/test/assistantPagination.integration.test.js +32 -42
- package/test/createHooksToCollectChildren.test.js +61 -16
- package/test/crudFeaturePackagePattern.test.js +50 -0
- package/test/crudOnHandles.test.js +454 -0
- package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
- package/test/errorCodes.test.js +11 -52
- package/test/hiddenFields.test.js +62 -0
- package/test/listQueryValidators.test.js +1 -1
- package/test/routeContracts.test.js +1 -1
- package/test/support/crudJsonApiActionOptions.js +3 -3
- package/test/unservedCrudAutomation.test.js +27 -22
- package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
- package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
- package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
- package/src/server/createCrudServiceFromResource.js +0 -63
- package/src/server/defineCrudJsonApiFeature.js +0 -346
- package/src/server/fieldAccess.js +0 -298
- package/src/server/jsonApiModule/repository.js +0 -355
- package/src/server/lookupPathSupport.js +0 -58
- package/src/server/lookups.js +0 -40
- package/src/server/repositorySupport.js +0 -528
- package/src/server/resourceRuntime/compiledRuntime.js +0 -284
- package/src/server/resourceRuntime/index.js +0 -659
- package/src/server/resourceRuntime/listControls.js +0 -333
- package/src/server/resourceRuntime/lookupHydration.js +0 -626
- package/src/server/resourceRuntime/operationStages.js +0 -140
- package/src/server/resourceRuntime/recordValidation.js +0 -65
- package/src/server/serviceMethods.js +0 -149
- package/test/createCrudServiceFromResource.test.js +0 -323
- package/test/fieldAccess.test.js +0 -86
- package/test/jsonApiRepository.test.js +0 -333
- package/test/jsonApiRepositoryDataCosts.test.js +0 -183
- package/test/jsonApiRepositoryPageLimits.test.js +0 -158
- package/test/jsonApiRepositoryRowLocks.test.js +0 -137
- package/test/jsonApiResourcePackagePattern.test.js +0 -20
- package/test/lookups.test.js +0 -111
- package/test/repositorySupport.test.js +0 -767
- package/test/resourceRuntime.test.js +0 -1014
- package/test/serviceMethods.test.js +0 -139
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
- /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
|
@@ -14,6 +14,7 @@ import {
|
|
|
14
14
|
import { buildCrudRecordChangedEvent, resolveCrudJsonApiEntityIdFromResult } from "../serviceEvents.js";
|
|
15
15
|
import { createCrudAssistantExtension } from "./assistantExtension.js";
|
|
16
16
|
import { buildCrudCustomActionId } from "./customActionId.js";
|
|
17
|
+
import { withRemovedProperties } from "../removedApi.js";
|
|
17
18
|
|
|
18
19
|
const CRUD_OPERATION_NAMES = Object.freeze(["list", "view", "create", "update", "delete"]);
|
|
19
20
|
const CRUD_MUTATION_NAMES = new Set(["create", "update", "delete"]);
|
|
@@ -96,26 +97,34 @@ function normalizeCrudOperationLifecycle(value) {
|
|
|
96
97
|
return Object.freeze(lifecycle);
|
|
97
98
|
}
|
|
98
99
|
|
|
100
|
+
// What a lifecycle hook's argument no longer carries.
|
|
101
|
+
const REMOVED_LIFECYCLE_PROPERTIES = Object.freeze({
|
|
102
|
+
trx: "pass options, which carries the operation's transaction, to each repository call."
|
|
103
|
+
});
|
|
104
|
+
|
|
99
105
|
function buildLifecycleContext(value) {
|
|
100
|
-
const { operation, input, context, resource, repository, service,
|
|
101
|
-
return Object.freeze({
|
|
106
|
+
const { operation, input, context, options, resource, repository, service, result, standard } = value;
|
|
107
|
+
return Object.freeze(withRemovedProperties({
|
|
102
108
|
operation,
|
|
103
109
|
input,
|
|
104
110
|
context,
|
|
111
|
+
options,
|
|
105
112
|
resource,
|
|
106
113
|
repository,
|
|
107
114
|
service,
|
|
108
|
-
trx,
|
|
109
115
|
...(Object.hasOwn(value, "result") ? { result } : {}),
|
|
110
116
|
...(standard ? { standard } : {})
|
|
111
|
-
});
|
|
117
|
+
}, REMOVED_LIFECYCLE_PROPERTIES, "A CRUD lifecycle hook's argument"));
|
|
112
118
|
}
|
|
113
119
|
|
|
114
120
|
function normalizeAdditionalActions(definitions, { namespace, surface, permissionForAction, scopeInputValidator, servedOverHttp }) {
|
|
115
121
|
return Object.freeze(Object.entries(definitions).map(([name, definition]) => {
|
|
116
122
|
const actionName = String(name || "").trim();
|
|
117
123
|
if (!ARCHITECTURE_ID_PATTERN.test(actionName)) {
|
|
118
|
-
throw new TypeError(
|
|
124
|
+
throw new TypeError(
|
|
125
|
+
`CRUD custom action name "${actionName}" is invalid: an action name is lower case, starts with a letter and ` +
|
|
126
|
+
"holds only letters, digits, _, . and - (cancel-day, not cancelDay)."
|
|
127
|
+
);
|
|
119
128
|
}
|
|
120
129
|
if (CRUD_OPERATION_NAMES.includes(actionName)) {
|
|
121
130
|
throw new TypeError(`CRUD custom action name "${actionName}" is reserved.`);
|
|
@@ -157,10 +166,10 @@ function normalizeAdditionalActions(definitions, { namespace, surface, permissio
|
|
|
157
166
|
|
|
158
167
|
/**
|
|
159
168
|
* The standard and custom actions of one CRUD feature, from the options
|
|
160
|
-
*
|
|
169
|
+
* defineCrudFeature resolved.
|
|
161
170
|
* @param {object} dependencies
|
|
162
171
|
* @param {string} dependencies.namespace
|
|
163
|
-
* @param {import("../types.js").
|
|
172
|
+
* @param {import("../types.js").CrudContract} dependencies.resource
|
|
164
173
|
* @param {import("../types.js").CrudRepository} dependencies.repository
|
|
165
174
|
* @param {import("../types.js").CrudService} dependencies.service
|
|
166
175
|
* @param {string} dependencies.surface
|
|
@@ -208,38 +217,39 @@ function createCrudJsonApiActions({
|
|
|
208
217
|
servedOverHttp
|
|
209
218
|
});
|
|
210
219
|
|
|
211
|
-
// HTTP and automation callers keep
|
|
212
|
-
//
|
|
220
|
+
// HTTP and automation callers keep the resource's page cap: a larger limit answers
|
|
221
|
+
// pageLimits().request records, and the response's pagination reports the page size, hasMore
|
|
213
222
|
// and the next cursor, as it always has. Server code asking for more gets an error instead.
|
|
214
|
-
function listDocuments(input,
|
|
223
|
+
function listDocuments(input, options) {
|
|
215
224
|
const query = omitInputKeys(input, scopeInputKeys);
|
|
216
|
-
|
|
217
|
-
|
|
225
|
+
const pageLimit = repository.pageLimits().request;
|
|
226
|
+
if (query.limit != null && Number(query.limit) > pageLimit) {
|
|
227
|
+
query.limit = pageLimit;
|
|
218
228
|
}
|
|
219
|
-
return service.
|
|
229
|
+
return service.list(query, options);
|
|
220
230
|
}
|
|
221
231
|
|
|
222
|
-
function viewDocument(input,
|
|
223
|
-
return service.
|
|
232
|
+
function viewDocument(input, options) {
|
|
233
|
+
return service.view(input.recordId, omitInputKeys(input, [...scopeInputKeys, "recordId"]), options);
|
|
224
234
|
}
|
|
225
235
|
|
|
226
|
-
function createDocument(input,
|
|
227
|
-
return service.
|
|
236
|
+
function createDocument(input, options) {
|
|
237
|
+
return service.create(omitInputKeys(input, scopeInputKeys), options);
|
|
228
238
|
}
|
|
229
239
|
|
|
230
|
-
function updateDocument(input,
|
|
231
|
-
return service.
|
|
240
|
+
function updateDocument(input, options) {
|
|
241
|
+
return service.patch(input.recordId, omitInputKeys(input, [...scopeInputKeys, "recordId"]), options);
|
|
232
242
|
}
|
|
233
243
|
|
|
234
|
-
function deleteDocument(input,
|
|
235
|
-
return service.
|
|
244
|
+
function deleteDocument(input, options) {
|
|
245
|
+
return service.delete(input.recordId, options);
|
|
236
246
|
}
|
|
237
247
|
|
|
238
248
|
/**
|
|
239
249
|
* An operation's result, checked where its events depend on it: a create
|
|
240
250
|
* returns the created record, with its id, as a tagged JSON:API result of a
|
|
241
251
|
* kind the HTTP transport encodes (returnJsonApiDocument, as the service's
|
|
242
|
-
*
|
|
252
|
+
* create and a lifecycle's standard() do, or returnJsonApiData), since
|
|
243
253
|
* its created and record-changed events read the record's id from it.
|
|
244
254
|
* @param {string} operation
|
|
245
255
|
* @param {unknown} result
|
|
@@ -248,7 +258,7 @@ function createCrudJsonApiActions({
|
|
|
248
258
|
if (operation === "create" && !resolveCrudJsonApiEntityIdFromResult({ result })) {
|
|
249
259
|
throw new TypeError(
|
|
250
260
|
`CRUD ${namespace} create must return the created record, with its id, as a tagged JSON:API result ` +
|
|
251
|
-
"(returnJsonApiDocument, as
|
|
261
|
+
"(returnJsonApiDocument, as the CRUD service's create() and a lifecycle's standard() do, or returnJsonApiData)."
|
|
252
262
|
);
|
|
253
263
|
}
|
|
254
264
|
return result;
|
|
@@ -259,20 +269,22 @@ function createCrudJsonApiActions({
|
|
|
259
269
|
* @param {string} operation
|
|
260
270
|
* @param {object} input
|
|
261
271
|
* @param {object} context
|
|
262
|
-
* @param {(input: object, context: object, trx
|
|
272
|
+
* @param {(input: object, options: { context: object, trx?: object }) => Promise<any>} runStandard
|
|
263
273
|
*/
|
|
264
274
|
async function executeOperation(operation, input, context, runStandard) {
|
|
265
275
|
const hooks = operationLifecycle[operation];
|
|
276
|
+
const callOptions = Object.freeze({ context });
|
|
266
277
|
if (!hooks) {
|
|
267
|
-
return requireOperationResult(operation, await runStandard(input,
|
|
278
|
+
return requireOperationResult(operation, await runStandard(input, callOptions));
|
|
268
279
|
}
|
|
269
280
|
|
|
270
|
-
|
|
271
|
-
|
|
281
|
+
// A mutation's hooks and its standard operation share one transaction: the options they receive carry it.
|
|
282
|
+
async function run(options) {
|
|
283
|
+
const base = { operation, input, context, options, resource, repository, service };
|
|
272
284
|
if (hooks.before) {
|
|
273
285
|
await hooks.before(buildLifecycleContext(base));
|
|
274
286
|
}
|
|
275
|
-
const standard = (nextInput = input) => runStandard(nextInput,
|
|
287
|
+
const standard = (nextInput = input) => runStandard(nextInput, options);
|
|
276
288
|
const result = requireOperationResult(operation, hooks.execute
|
|
277
289
|
? await hooks.execute(buildLifecycleContext({ ...base, standard }))
|
|
278
290
|
: await standard());
|
|
@@ -282,17 +294,19 @@ function createCrudJsonApiActions({
|
|
|
282
294
|
return result;
|
|
283
295
|
}
|
|
284
296
|
|
|
285
|
-
const result = CRUD_MUTATION_NAMES.has(operation)
|
|
297
|
+
const result = CRUD_MUTATION_NAMES.has(operation)
|
|
298
|
+
? await repository.withTransaction(callOptions, run)
|
|
299
|
+
: await run(callOptions);
|
|
286
300
|
if (hooks.afterCommit) {
|
|
287
301
|
try {
|
|
288
302
|
await hooks.afterCommit(buildLifecycleContext({
|
|
289
303
|
operation,
|
|
290
304
|
input,
|
|
291
305
|
context,
|
|
306
|
+
options: callOptions,
|
|
292
307
|
resource,
|
|
293
308
|
repository,
|
|
294
309
|
service,
|
|
295
|
-
trx: null,
|
|
296
310
|
result
|
|
297
311
|
}));
|
|
298
312
|
} catch (error) {
|
|
@@ -75,11 +75,11 @@ function normalizeCustomActionRoutes(actions, namespace) {
|
|
|
75
75
|
}
|
|
76
76
|
|
|
77
77
|
/**
|
|
78
|
-
* Registers the routes of one CRUD feature, from the options
|
|
78
|
+
* Registers the routes of one CRUD feature, from the options defineCrudFeature resolved.
|
|
79
79
|
* @param {import("@jskit-ai/kernel/server/types").RuntimeRouter} router
|
|
80
80
|
* @param {object} options
|
|
81
81
|
* @param {string} options.namespace
|
|
82
|
-
* @param {import("../types.js").
|
|
82
|
+
* @param {import("../types.js").CrudContract} options.resource
|
|
83
83
|
* @param {string} options.routeBase
|
|
84
84
|
* @param {string} options.relativePath
|
|
85
85
|
* @param {string} options.surface
|
|
@@ -1,61 +1,242 @@
|
|
|
1
1
|
import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
|
|
2
|
-
import { resolveTransaction } from "@jskit-ai/database-runtime/shared";
|
|
3
2
|
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
3
|
+
import { buildJsonRestQueryParams, passedOn } from "@jskit-ai/resource-runtime/server";
|
|
4
|
+
import {
|
|
5
|
+
resolveDeclaredLookupContainerKey,
|
|
6
|
+
resolveJsonApiRelationshipEntries,
|
|
7
|
+
resolveSchemaFieldDefinitions
|
|
8
|
+
} from "../jsonApiResourceContract.js";
|
|
9
|
+
|
|
10
|
+
// A record that is missing or out of the caller's scope.
|
|
11
|
+
function documentNotFound() {
|
|
12
|
+
return new AppError(404, "Document not found.", { code: "crud.document.notFound" });
|
|
13
|
+
}
|
|
4
14
|
|
|
5
15
|
function requireDocument(document) {
|
|
6
16
|
if (!document) {
|
|
7
|
-
throw
|
|
17
|
+
throw documentNotFound();
|
|
8
18
|
}
|
|
9
19
|
return document;
|
|
10
20
|
}
|
|
11
21
|
|
|
22
|
+
// json-rest-api's not-found error, classified by its code.
|
|
23
|
+
function isNotFound(error) {
|
|
24
|
+
return error?.code === "REST_API_RESOURCE" && error?.subtype === "not_found";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A contract's record output: its view (or create, replace, patch) output, or a list-only contract's list item.
|
|
29
|
+
* @param {import("../types.js").CrudContract} crud
|
|
30
|
+
*/
|
|
31
|
+
function recordOutput(crud) {
|
|
32
|
+
const record = ["view", "create", "replace", "patch"].map((name) => crud.operations[name]?.output).find(Boolean);
|
|
33
|
+
return record || { schema: resolveSchemaFieldDefinitions(crud.operations.list?.output).items?.items };
|
|
34
|
+
}
|
|
35
|
+
|
|
12
36
|
/**
|
|
13
|
-
* What a
|
|
14
|
-
*
|
|
15
|
-
* @param {
|
|
37
|
+
* What a contract shows of its own records: the attributes its record output names, and the relationships of the
|
|
38
|
+
* fields it names.
|
|
39
|
+
* @param {import("../types.js").CrudContract} crud
|
|
16
40
|
*/
|
|
17
|
-
function
|
|
18
|
-
|
|
41
|
+
function contractShape(crud) {
|
|
42
|
+
const output = recordOutput(crud);
|
|
43
|
+
const lookupContainerKey = resolveDeclaredLookupContainerKey(crud);
|
|
44
|
+
const relationships = resolveJsonApiRelationshipEntries(output);
|
|
45
|
+
return {
|
|
46
|
+
attributes: new Set(Object.keys(resolveSchemaFieldDefinitions(output)).filter((key) => key !== lookupContainerKey)),
|
|
47
|
+
relationshipNames: new Set(relationships.map(({ relationshipName }) => relationshipName)),
|
|
48
|
+
relationships
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* What an included record shows, from what its relation lists (see includeFieldsOf): its label and listed fields, the
|
|
54
|
+
* relationships the list names, and for each of those what its records show.
|
|
55
|
+
* @param {{ attributes: ReadonlyArray<string>, relationships: Readonly<Record<string, any>> }} include
|
|
56
|
+
* @param {string} [labelKey]
|
|
57
|
+
*/
|
|
58
|
+
function includedShape({ attributes, relationships }, labelKey = "") {
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
attributes: new Set([labelKey, ...attributes].filter(Boolean)),
|
|
61
|
+
relationshipNames: new Set(Object.keys(relationships)),
|
|
62
|
+
linked: new Map(Object.entries(relationships).map(([name, nested]) => [name, includedShape(nested)]))
|
|
63
|
+
});
|
|
19
64
|
}
|
|
20
65
|
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
66
|
+
/**
|
|
67
|
+
* What the documents of a contract show of the records its includes reach, by relationship. An included record shows
|
|
68
|
+
* its id, its relation's `labelKey` and what the contract's relation lists in `includeFields`, at every depth; it
|
|
69
|
+
* never takes another contract's output, so a contract served to another surface or behind another permission shapes
|
|
70
|
+
* nothing here.
|
|
71
|
+
* @param {import("../types.js").CrudContract} crud
|
|
72
|
+
* @returns {Map<string, ReturnType<typeof includedShape>>}
|
|
73
|
+
*/
|
|
74
|
+
function documentShapes(crud) {
|
|
75
|
+
return new Map(contractShape(crud).relationships.map((entry) => [entry.relationshipName, includedShape(entry.include, entry.labelKey)]));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The CRUD service: the HTTP edge of a CRUD feature. It takes an operation's
|
|
80
|
+
* HTTP query and body, calls the feature's repository (its table's handle, as
|
|
81
|
+
* decorated) with the call's options and `format: "jsonapi"`, and answers
|
|
82
|
+
* JSON:API documents that show only what the CRUD contract names: its records'
|
|
83
|
+
* attributes and relationships, and each included record with only what its
|
|
84
|
+
* relation names (see documentShapes), so a column or relationship the
|
|
85
|
+
* contract does not name is never answered.
|
|
86
|
+
* Server code calls the repository instead. The handle stamps the table's
|
|
87
|
+
* createdAt and updatedAt, as it does for every write.
|
|
88
|
+
* @param {object} dependencies
|
|
89
|
+
* @param {import("../types.js").CrudRepository} dependencies.repository
|
|
90
|
+
* @param {import("../types.js").CrudContract} dependencies.crud The CRUD contract the service answers for.
|
|
91
|
+
*/
|
|
92
|
+
function createCrudService({ repository, crud }) {
|
|
93
|
+
const resourceName = crud.resource.name;
|
|
94
|
+
const own = contractShape(crud);
|
|
95
|
+
const shapes = documentShapes(crud);
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @param {Record<string, any>} record A JSON:API resource object.
|
|
99
|
+
* @param {{ attributes: Set<string>, relationshipNames: Set<string> }} shape
|
|
100
|
+
*/
|
|
101
|
+
function shownRecord(record, shape) {
|
|
102
|
+
const shown = { ...record };
|
|
103
|
+
if (record.attributes) {
|
|
104
|
+
shown.attributes = Object.fromEntries(Object.entries(record.attributes).filter(([key]) => shape.attributes.has(key)));
|
|
105
|
+
}
|
|
106
|
+
if (record.relationships) {
|
|
107
|
+
shown.relationships = Object.fromEntries(Object.entries(record.relationships).filter(([name]) => shape.relationshipNames.has(name)));
|
|
108
|
+
}
|
|
109
|
+
return shown;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Each record a relationship the shapes name links to, with what it shows: [(type, id) key, shape] pairs.
|
|
114
|
+
* @param {Record<string, any>} record
|
|
115
|
+
* @param {Map<string, ReturnType<typeof includedShape>>} linked The shapes of the relationships kept, by name.
|
|
116
|
+
*/
|
|
117
|
+
function linkedRecords(record, linked) {
|
|
118
|
+
return Object.entries(record.relationships || {}).flatMap(([name, { data }]) => {
|
|
119
|
+
const shape = linked.get(name);
|
|
120
|
+
return shape ? (Array.isArray(data) ? data : data ? [data] : []).map(({ type, id }) => [`${type}:${id}`, shape]) : [];
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The document as the contract shows it: its records, and only the included records a kept relationship reaches,
|
|
126
|
+
* each shaped by what the contract lists for every relationship that reaches it.
|
|
127
|
+
* @param {Record<string, any> | null} document
|
|
128
|
+
*/
|
|
129
|
+
function answer(document) {
|
|
130
|
+
if (!document?.data) {
|
|
131
|
+
return returnJsonApiDocument(document);
|
|
132
|
+
}
|
|
133
|
+
const records = (Array.isArray(document.data) ? document.data : [document.data]).map((record) => shownRecord(record, own));
|
|
134
|
+
const shown = { ...document, data: Array.isArray(document.data) ? records : records[0] };
|
|
135
|
+
if (document.included) {
|
|
136
|
+
const included = new Map(document.included.map((record) => [`${record.type}:${record.id}`, record]));
|
|
137
|
+
/** @type {Map<string, Set<ReturnType<typeof includedShape>>>} The shapes that reach each included record. */
|
|
138
|
+
const reachedBy = new Map();
|
|
139
|
+
const pending = records.flatMap((record) => linkedRecords(record, shapes));
|
|
140
|
+
while (pending.length > 0) {
|
|
141
|
+
const [key, shape] = pending.pop();
|
|
142
|
+
const shapesOfRecord = reachedBy.get(key) ?? new Set();
|
|
143
|
+
if (!included.has(key) || shapesOfRecord.has(shape)) continue;
|
|
144
|
+
reachedBy.set(key, shapesOfRecord.add(shape));
|
|
145
|
+
pending.push(...linkedRecords(included.get(key), shape.linked));
|
|
146
|
+
}
|
|
147
|
+
shown.included = document.included.flatMap((record) => {
|
|
148
|
+
const reaching = [...(reachedBy.get(`${record.type}:${record.id}`) ?? [])];
|
|
149
|
+
return reaching.length < 1 ? [] : [shownRecord(record, {
|
|
150
|
+
attributes: new Set(reaching.flatMap((shape) => [...shape.attributes])),
|
|
151
|
+
relationshipNames: new Set(reaching.flatMap((shape) => [...shape.relationshipNames]))
|
|
152
|
+
})];
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
return returnJsonApiDocument(shown);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* What the repository, or a decorator over it, receives: the caller's context and transaction, and the one setting
|
|
160
|
+
* the service names, JSON:API documents. A decorator passes only `{ context, trx }` on to another table.
|
|
161
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
162
|
+
*/
|
|
163
|
+
function documentOptions(options) {
|
|
164
|
+
return { ...passedOn(options), format: "jsonapi" };
|
|
25
165
|
}
|
|
26
166
|
|
|
27
|
-
|
|
28
|
-
|
|
167
|
+
/**
|
|
168
|
+
* One page of the records the HTTP query matches: its filters, `include`,
|
|
169
|
+
* `fields`, `sort`, `limit` and `cursor`.
|
|
170
|
+
* @param {Record<string, unknown>} query
|
|
171
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
172
|
+
*/
|
|
173
|
+
async function list(query, options) {
|
|
174
|
+
return answer(await repository.query(buildJsonRestQueryParams(resourceName, query), documentOptions(options)));
|
|
29
175
|
}
|
|
30
176
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
177
|
+
/**
|
|
178
|
+
* @param {unknown} recordId
|
|
179
|
+
* @param {Record<string, unknown>} query `include` and `fields`.
|
|
180
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
181
|
+
*/
|
|
182
|
+
async function view(recordId, query, options) {
|
|
183
|
+
if (options && Object.hasOwn(options, "forUpdate")) {
|
|
184
|
+
throw new TypeError(
|
|
185
|
+
"The CRUD service's view() no longer takes forUpdate: lock the record with the repository's " +
|
|
186
|
+
"lock(recordId, txOptions) inside repository.withTransaction(options, (txOptions) => ...)."
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
try {
|
|
190
|
+
return answer(requireDocument(await repository.get(recordId, buildJsonRestQueryParams(resourceName, query), documentOptions(options))));
|
|
191
|
+
} catch (error) {
|
|
192
|
+
throw isNotFound(error) ? documentNotFound() : error;
|
|
193
|
+
}
|
|
37
194
|
}
|
|
38
195
|
|
|
39
|
-
|
|
40
|
-
|
|
196
|
+
/**
|
|
197
|
+
* @param {Record<string, unknown>} payload
|
|
198
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
199
|
+
*/
|
|
200
|
+
async function create(payload, options) {
|
|
201
|
+
return answer(await repository.create(payload, documentOptions(options)));
|
|
41
202
|
}
|
|
42
203
|
|
|
43
|
-
|
|
44
|
-
|
|
204
|
+
/**
|
|
205
|
+
* @param {unknown} recordId
|
|
206
|
+
* @param {Record<string, unknown>} payload
|
|
207
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
208
|
+
*/
|
|
209
|
+
async function patch(recordId, payload, options) {
|
|
210
|
+
try {
|
|
211
|
+
return answer(requireDocument(
|
|
212
|
+
await repository.patch(recordId, payload, documentOptions(options))
|
|
213
|
+
));
|
|
214
|
+
} catch (error) {
|
|
215
|
+
throw isNotFound(error) ? documentNotFound() : error;
|
|
216
|
+
}
|
|
45
217
|
}
|
|
46
218
|
|
|
47
|
-
|
|
48
|
-
|
|
219
|
+
/**
|
|
220
|
+
* Deletes the record and answers its id; a record that is already gone answers null.
|
|
221
|
+
* @param {unknown} recordId
|
|
222
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
223
|
+
*/
|
|
224
|
+
async function deleteRecord(recordId, options) {
|
|
225
|
+
try {
|
|
226
|
+
return await repository.delete(recordId, passedOn(options));
|
|
227
|
+
} catch (error) {
|
|
228
|
+
if (isNotFound(error)) return null;
|
|
229
|
+
throw error;
|
|
230
|
+
}
|
|
49
231
|
}
|
|
50
232
|
|
|
51
233
|
return Object.freeze({
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
deleteDocumentById
|
|
234
|
+
list,
|
|
235
|
+
view,
|
|
236
|
+
create,
|
|
237
|
+
patch,
|
|
238
|
+
delete: deleteRecord
|
|
58
239
|
});
|
|
59
240
|
}
|
|
60
241
|
|
|
61
|
-
export {
|
|
242
|
+
export { createCrudService };
|
|
@@ -12,6 +12,44 @@ function resolveSchemaFieldDefinitions(definition = null) {
|
|
|
12
12
|
return isRecord(definitions) ? definitions : {};
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
const NOTHING_INCLUDED = Object.freeze({ attributes: Object.freeze([]), relationships: Object.freeze({}) });
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* What a CRUD contract shows of a record it includes, beyond its id and label: its relation field's output entry's
|
|
19
|
+
* `includeFields`, the included record's fields and, as `{ relationship: [...] }`, the records it links to with what
|
|
20
|
+
* each of them shows, at any depth: `fields: { petId: { output: { required: false, includeFields: ["name", { breed:
|
|
21
|
+
* ["name"] }] } } }`. Nothing else of an included record is shown.
|
|
22
|
+
* @param {string} label Where the list is, such as "petId.includeFields".
|
|
23
|
+
* @param {unknown} names
|
|
24
|
+
* @returns {{ attributes: ReadonlyArray<string>, relationships: Readonly<Record<string, any>> }}
|
|
25
|
+
*/
|
|
26
|
+
function includeFieldsOf(label, names) {
|
|
27
|
+
if (names === undefined) {
|
|
28
|
+
return NOTHING_INCLUDED;
|
|
29
|
+
}
|
|
30
|
+
const attributes = [];
|
|
31
|
+
const relationships = {};
|
|
32
|
+
// A list that is not one is refused as its one malformed entry.
|
|
33
|
+
for (const name of Array.isArray(names) ? names : [null]) {
|
|
34
|
+
if (typeof name === "string" && normalizeText(name)) {
|
|
35
|
+
attributes.push(normalizeText(name));
|
|
36
|
+
} else if (isRecord(name) && Object.keys(name).length > 0 && Object.entries(name).every(([key, nested]) => normalizeText(key) && Array.isArray(nested))) {
|
|
37
|
+
for (const [relationshipName, nested] of Object.entries(name)) {
|
|
38
|
+
relationships[relationshipName] = includeFieldsOf(`${label}.${relationshipName}`, nested);
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
throw new TypeError(
|
|
42
|
+
`A CRUD contract's ${label} must list the fields an included record shows: field names, ` +
|
|
43
|
+
"and { relationship: [...] } for a record it links to."
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return Object.freeze({
|
|
48
|
+
attributes: Object.freeze(attributes),
|
|
49
|
+
relationships: Object.freeze(relationships)
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
15
53
|
function resolveJsonApiRelationshipEntries(definition = null) {
|
|
16
54
|
const entries = [];
|
|
17
55
|
|
|
@@ -29,6 +67,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
|
|
|
29
67
|
relationshipName,
|
|
30
68
|
relationshipType,
|
|
31
69
|
labelKey: normalizeText(normalizedFieldDefinition.relation?.labelKey),
|
|
70
|
+
include: includeFieldsOf(`${fieldKey}.includeFields`, normalizedFieldDefinition.includeFields),
|
|
32
71
|
required: normalizedFieldDefinition.required === true,
|
|
33
72
|
nullable: normalizedFieldDefinition.nullable === true
|
|
34
73
|
}));
|
|
@@ -59,6 +98,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
|
|
|
59
98
|
relationshipName: collectionRelationshipName,
|
|
60
99
|
relationshipType: collectionRelationshipType,
|
|
61
100
|
labelKey: normalizeText(relation.labelKey),
|
|
101
|
+
include: includeFieldsOf(`${fieldKey}.includeFields`, normalizedFieldDefinition.includeFields),
|
|
62
102
|
many: true,
|
|
63
103
|
required: normalizedFieldDefinition.required === true,
|
|
64
104
|
nullable: normalizedFieldDefinition.nullable === true
|
|
@@ -70,7 +110,7 @@ function resolveJsonApiRelationshipEntries(definition = null) {
|
|
|
70
110
|
|
|
71
111
|
/**
|
|
72
112
|
* The lookup container key a resource's contract declares, or "" when it declares none.
|
|
73
|
-
* @param {import("./types.js").
|
|
113
|
+
* @param {import("./types.js").CrudContract} resource
|
|
74
114
|
*/
|
|
75
115
|
function resolveDeclaredLookupContainerKey(resource) {
|
|
76
116
|
return normalizeText(resource.contract?.lookup?.containerKey);
|
|
@@ -214,7 +214,7 @@ function createStandardCrudListQueryValidators({
|
|
|
214
214
|
|
|
215
215
|
return Object.freeze([
|
|
216
216
|
createCrudCursorPaginationQueryValidator({
|
|
217
|
-
orderBy: resource.defaultSort
|
|
217
|
+
orderBy: resource.resource?.defaultSort
|
|
218
218
|
}),
|
|
219
219
|
searchQueryValidator,
|
|
220
220
|
createCrudParentFilterQueryValidator(resource),
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// The CRUD API names the data-access redesign removed, each with its replacement, so code written for the earlier
|
|
2
|
+
// API fails where it names one instead of being silently ignored or reading undefined.
|
|
3
|
+
|
|
4
|
+
// Repository methods of the earlier CRUD repository and its helpers, and what a table's handle offers instead.
|
|
5
|
+
const LEGACY_REPOSITORY_METHODS = Object.freeze({
|
|
6
|
+
queryDocuments: "query({ page: { size } }, options)",
|
|
7
|
+
getDocumentById: "get(id, params, options)",
|
|
8
|
+
queryAllJsonRestCollectionRows: "queryAll(params, options)",
|
|
9
|
+
queryEveryDocument: "queryAll(params, options)",
|
|
10
|
+
createDocument: "create(attributes, options)",
|
|
11
|
+
createDocuments: "createMany(rows, options)",
|
|
12
|
+
patchDocumentById: "patch(id, changes, options)",
|
|
13
|
+
patchDocumentIfLockVersion: "patch(id, changes, { ...options, lockVersion })",
|
|
14
|
+
deleteDocumentById: "delete(id, options)",
|
|
15
|
+
applyForUpdate: "lock(id, txOptions) inside withTransaction",
|
|
16
|
+
lockScopedRecordId: "lock(id, txOptions) inside withTransaction",
|
|
17
|
+
runInTransaction: "withTransaction(options, (txOptions) => ...)",
|
|
18
|
+
createWithTransaction: "withTransaction(options, (txOptions) => ...)",
|
|
19
|
+
joinOrOpenTransaction: "withTransaction(options, (txOptions) => ...)",
|
|
20
|
+
resolveTransaction: "withTransaction(options, (txOptions) => ...)",
|
|
21
|
+
resolveQueryOptions: "the options every handle call takes last",
|
|
22
|
+
resolveRepoClient: "withTransaction(options, (txOptions) => ...)"
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// Methods of the earlier CRUD services, and the CRUD service method the routes and actions now call instead.
|
|
26
|
+
const LEGACY_SERVICE_METHODS = Object.freeze({
|
|
27
|
+
queryDocuments: "list(query, options)",
|
|
28
|
+
queryEveryDocument: "list(query, options), or the repository's queryAll(params, options) for every record",
|
|
29
|
+
getDocumentById: "view(recordId, query, options)",
|
|
30
|
+
createDocument: "create(payload, options)",
|
|
31
|
+
patchDocumentById: "patch(recordId, payload, options)",
|
|
32
|
+
deleteDocumentById: "delete(recordId, options)",
|
|
33
|
+
listRecords: "list(query, options)",
|
|
34
|
+
getRecord: "view(recordId, query, options)",
|
|
35
|
+
createRecord: "create(payload, options)",
|
|
36
|
+
updateRecord: "patch(recordId, payload, options)",
|
|
37
|
+
deleteRecord: "delete(recordId, options)"
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Refuses a decorated repository or service that still defines a method of the
|
|
42
|
+
* earlier API: nothing calls it any more, so its behaviour would be lost.
|
|
43
|
+
* @param {object} target
|
|
44
|
+
* @param {Readonly<Record<string, string>>} legacyMethods
|
|
45
|
+
* @param {string} label What returned the target, for the message.
|
|
46
|
+
*/
|
|
47
|
+
function rejectLegacyMethods(target, legacyMethods, label) {
|
|
48
|
+
if (!target || typeof target !== "object") {
|
|
49
|
+
return target;
|
|
50
|
+
}
|
|
51
|
+
const found = Object.keys(legacyMethods).filter((name) => name in target);
|
|
52
|
+
if (found.length > 0) {
|
|
53
|
+
throw new TypeError(
|
|
54
|
+
`${label} defines ${found.map((name) => `${name}()`).join(", ")}, which nothing calls since the data-access ` +
|
|
55
|
+
`redesign, so its behaviour would be lost. Rename each to its replacement: ` +
|
|
56
|
+
`${found.map((name) => `${name}() is now ${legacyMethods[name]}`).join("; ")}.`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
return target;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Gives `target` a non-enumerable getter for each removed property it does not
|
|
64
|
+
* hold, which throws naming the replacement. Spreading the target skips them;
|
|
65
|
+
* reading one, as destructuring does, throws. Call it before freezing.
|
|
66
|
+
* @template {object} T
|
|
67
|
+
* @param {T} target
|
|
68
|
+
* @param {Readonly<Record<string, string>>} removed Each removed name and what replaced it.
|
|
69
|
+
* @param {string} label What the target is, for the message.
|
|
70
|
+
* @returns {T}
|
|
71
|
+
*/
|
|
72
|
+
function withRemovedProperties(target, removed, label) {
|
|
73
|
+
for (const [name, replacement] of Object.entries(removed)) {
|
|
74
|
+
if (Object.hasOwn(target, name)) {
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
Object.defineProperty(target, name, {
|
|
78
|
+
enumerable: false,
|
|
79
|
+
get() {
|
|
80
|
+
throw new TypeError(`${label} no longer has ${name}: ${replacement}`);
|
|
81
|
+
}
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return target;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export { LEGACY_REPOSITORY_METHODS, LEGACY_SERVICE_METHODS, rejectLegacyMethods, withRemovedProperties };
|