@jskit-ai/crud-core 0.2.14 → 0.2.16
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 +21 -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 +538 -0
- package/src/server/jsonApiModule/actions.js +117 -59
- package/src/server/jsonApiModule/routes.js +35 -11
- package/src/server/jsonApiModule/service.js +227 -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 +51 -0
- package/test/crudOnHandles.test.js +451 -0
- package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +451 -141
- package/test/errorCodes.test.js +11 -52
- package/test/hiddenFields.test.js +63 -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
|
@@ -1,61 +1,256 @@
|
|
|
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
|
+
|
|
12
27
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* @param {{ trx?: import("@jskit-ai/database-runtime/server/types").RuntimeKnexTransaction | null, context?: object | null }} [options]
|
|
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
|
|
16
30
|
*/
|
|
17
|
-
function
|
|
18
|
-
|
|
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 };
|
|
19
34
|
}
|
|
20
35
|
|
|
21
|
-
/**
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
36
|
+
/**
|
|
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
|
|
40
|
+
*/
|
|
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
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
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
|
+
// What each CRUD contract shows, by contract. defineCrudContract deep-freezes a contract, so what it shows is worked
|
|
79
|
+
// out once and every service on it reads the same shapes; a contract whose shapes throw keeps nothing.
|
|
80
|
+
const shapesByContract = new WeakMap();
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* What a contract's documents show: its own records' shape and its includes' shapes.
|
|
84
|
+
* @param {import("../types.js").CrudContract} crud
|
|
85
|
+
*/
|
|
86
|
+
function contractShapes(crud) {
|
|
87
|
+
if (!shapesByContract.has(crud)) {
|
|
88
|
+
shapesByContract.set(crud, Object.freeze({ own: contractShape(crud), linked: documentShapes(crud) }));
|
|
89
|
+
}
|
|
90
|
+
return shapesByContract.get(crud);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* The CRUD service: the HTTP edge of a CRUD feature. It takes an operation's
|
|
95
|
+
* HTTP query and body, calls the feature's repository (its table's handle, as
|
|
96
|
+
* decorated) with the call's options and `format: "jsonapi"`, and answers
|
|
97
|
+
* JSON:API documents that show only what the CRUD contract names: its records'
|
|
98
|
+
* attributes and relationships, and each included record with only what its
|
|
99
|
+
* relation names (see documentShapes), so a column or relationship the
|
|
100
|
+
* contract does not name is never answered.
|
|
101
|
+
* Server code calls the repository instead. The handle stamps the table's
|
|
102
|
+
* createdAt and updatedAt, as it does for every write.
|
|
103
|
+
* @param {object} dependencies
|
|
104
|
+
* @param {import("../types.js").CrudRepository} dependencies.repository
|
|
105
|
+
* @param {import("../types.js").CrudContract} dependencies.crud The CRUD contract the service answers for.
|
|
106
|
+
*/
|
|
107
|
+
function createCrudService({ repository, crud }) {
|
|
108
|
+
const resourceName = crud.resource.name;
|
|
109
|
+
const { own, linked: shapes } = contractShapes(crud);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @param {Record<string, any>} record A JSON:API resource object.
|
|
113
|
+
* @param {{ attributes: Set<string>, relationshipNames: Set<string> }} shape
|
|
114
|
+
*/
|
|
115
|
+
function shownRecord(record, shape) {
|
|
116
|
+
const shown = { ...record };
|
|
117
|
+
if (record.attributes) {
|
|
118
|
+
shown.attributes = Object.fromEntries(Object.entries(record.attributes).filter(([key]) => shape.attributes.has(key)));
|
|
119
|
+
}
|
|
120
|
+
if (record.relationships) {
|
|
121
|
+
shown.relationships = Object.fromEntries(Object.entries(record.relationships).filter(([name]) => shape.relationshipNames.has(name)));
|
|
122
|
+
}
|
|
123
|
+
return shown;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Each record a relationship the shapes name links to, with what it shows: [(type, id) key, shape] pairs.
|
|
128
|
+
* @param {Record<string, any>} record
|
|
129
|
+
* @param {Map<string, ReturnType<typeof includedShape>>} linked The shapes of the relationships kept, by name.
|
|
130
|
+
*/
|
|
131
|
+
function linkedRecords(record, linked) {
|
|
132
|
+
return Object.entries(record.relationships || {}).flatMap(([name, { data }]) => {
|
|
133
|
+
const shape = linked.get(name);
|
|
134
|
+
return shape ? (Array.isArray(data) ? data : data ? [data] : []).map(({ type, id }) => [`${type}:${id}`, shape]) : [];
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The document as the contract shows it: its records, and only the included records a kept relationship reaches,
|
|
140
|
+
* each shaped by what the contract lists for every relationship that reaches it.
|
|
141
|
+
* @param {Record<string, any> | null} document
|
|
142
|
+
*/
|
|
143
|
+
function answer(document) {
|
|
144
|
+
if (!document?.data) {
|
|
145
|
+
return returnJsonApiDocument(document);
|
|
146
|
+
}
|
|
147
|
+
const records = (Array.isArray(document.data) ? document.data : [document.data]).map((record) => shownRecord(record, own));
|
|
148
|
+
const shown = { ...document, data: Array.isArray(document.data) ? records : records[0] };
|
|
149
|
+
if (document.included) {
|
|
150
|
+
const included = new Map(document.included.map((record) => [`${record.type}:${record.id}`, record]));
|
|
151
|
+
/** @type {Map<string, Set<ReturnType<typeof includedShape>>>} The shapes that reach each included record. */
|
|
152
|
+
const reachedBy = new Map();
|
|
153
|
+
const pending = records.flatMap((record) => linkedRecords(record, shapes));
|
|
154
|
+
while (pending.length > 0) {
|
|
155
|
+
const [key, shape] = pending.pop();
|
|
156
|
+
const shapesOfRecord = reachedBy.get(key) ?? new Set();
|
|
157
|
+
if (!included.has(key) || shapesOfRecord.has(shape)) continue;
|
|
158
|
+
reachedBy.set(key, shapesOfRecord.add(shape));
|
|
159
|
+
pending.push(...linkedRecords(included.get(key), shape.linked));
|
|
160
|
+
}
|
|
161
|
+
shown.included = document.included.flatMap((record) => {
|
|
162
|
+
const reaching = [...(reachedBy.get(`${record.type}:${record.id}`) ?? [])];
|
|
163
|
+
return reaching.length < 1 ? [] : [shownRecord(record, {
|
|
164
|
+
attributes: new Set(reaching.flatMap((shape) => [...shape.attributes])),
|
|
165
|
+
relationshipNames: new Set(reaching.flatMap((shape) => [...shape.relationshipNames]))
|
|
166
|
+
})];
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
return returnJsonApiDocument(shown);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* What the repository, or a decorator over it, receives: the caller's context and transaction, and the one setting
|
|
174
|
+
* the service names, JSON:API documents. A decorator passes only `{ context, trx }` on to another table.
|
|
175
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
176
|
+
*/
|
|
177
|
+
function documentOptions(options) {
|
|
178
|
+
return { ...passedOn(options), format: "jsonapi" };
|
|
25
179
|
}
|
|
26
180
|
|
|
27
|
-
|
|
28
|
-
|
|
181
|
+
/**
|
|
182
|
+
* One page of the records the HTTP query matches: its filters, `include`,
|
|
183
|
+
* `fields`, `sort`, `limit` and `cursor`.
|
|
184
|
+
* @param {Record<string, unknown>} query
|
|
185
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
186
|
+
*/
|
|
187
|
+
async function list(query, options) {
|
|
188
|
+
return answer(await repository.query(buildJsonRestQueryParams(resourceName, query), documentOptions(options)));
|
|
29
189
|
}
|
|
30
190
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
191
|
+
/**
|
|
192
|
+
* @param {unknown} recordId
|
|
193
|
+
* @param {Record<string, unknown>} query `include` and `fields`.
|
|
194
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
195
|
+
*/
|
|
196
|
+
async function view(recordId, query, options) {
|
|
197
|
+
if (options && Object.hasOwn(options, "forUpdate")) {
|
|
198
|
+
throw new TypeError(
|
|
199
|
+
"The CRUD service's view() no longer takes forUpdate: lock the record with the repository's " +
|
|
200
|
+
"lock(recordId, txOptions) inside repository.withTransaction(options, (txOptions) => ...)."
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
try {
|
|
204
|
+
return answer(requireDocument(await repository.get(recordId, buildJsonRestQueryParams(resourceName, query), documentOptions(options))));
|
|
205
|
+
} catch (error) {
|
|
206
|
+
throw isNotFound(error) ? documentNotFound() : error;
|
|
207
|
+
}
|
|
37
208
|
}
|
|
38
209
|
|
|
39
|
-
|
|
40
|
-
|
|
210
|
+
/**
|
|
211
|
+
* @param {Record<string, unknown>} payload
|
|
212
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
213
|
+
*/
|
|
214
|
+
async function create(payload, options) {
|
|
215
|
+
return answer(await repository.create(payload, documentOptions(options)));
|
|
41
216
|
}
|
|
42
217
|
|
|
43
|
-
|
|
44
|
-
|
|
218
|
+
/**
|
|
219
|
+
* @param {unknown} recordId
|
|
220
|
+
* @param {Record<string, unknown>} payload
|
|
221
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
222
|
+
*/
|
|
223
|
+
async function patch(recordId, payload, options) {
|
|
224
|
+
try {
|
|
225
|
+
return answer(requireDocument(
|
|
226
|
+
await repository.patch(recordId, payload, documentOptions(options))
|
|
227
|
+
));
|
|
228
|
+
} catch (error) {
|
|
229
|
+
throw isNotFound(error) ? documentNotFound() : error;
|
|
230
|
+
}
|
|
45
231
|
}
|
|
46
232
|
|
|
47
|
-
|
|
48
|
-
|
|
233
|
+
/**
|
|
234
|
+
* Deletes the record and answers its id; a record that is already gone answers null.
|
|
235
|
+
* @param {unknown} recordId
|
|
236
|
+
* @param {{ context?: object | null, trx?: object | null }} options
|
|
237
|
+
*/
|
|
238
|
+
async function deleteRecord(recordId, options) {
|
|
239
|
+
try {
|
|
240
|
+
return await repository.delete(recordId, passedOn(options));
|
|
241
|
+
} catch (error) {
|
|
242
|
+
if (isNotFound(error)) return null;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
49
245
|
}
|
|
50
246
|
|
|
51
247
|
return Object.freeze({
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
deleteDocumentById
|
|
248
|
+
list,
|
|
249
|
+
view,
|
|
250
|
+
create,
|
|
251
|
+
patch,
|
|
252
|
+
delete: deleteRecord
|
|
58
253
|
});
|
|
59
254
|
}
|
|
60
255
|
|
|
61
|
-
export {
|
|
256
|
+
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 };
|
package/src/server/types.js
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
// The types of the capability a CRUD feature provides, for features that require it,
|
|
2
|
-
// of what its custom actions
|
|
2
|
+
// and of what its custom actions and lifecycle hooks receive.
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
6
|
-
* @typedef {object}
|
|
5
|
+
* One table's description, as defineTableResource returns it.
|
|
6
|
+
* @typedef {object} TableResource
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* The
|
|
11
|
-
*
|
|
10
|
+
* The CRUD surface a CRUD feature serves, as defineCrudContract returns it; its
|
|
11
|
+
* table resource is its `resource`.
|
|
12
|
+
* @typedef {object} CrudContract
|
|
12
13
|
*/
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
|
-
* The
|
|
16
|
-
*
|
|
16
|
+
* The repository a CRUD feature provides as its capability's `repository`: its
|
|
17
|
+
* CRUD table's handle, as decorateRepository returns it.
|
|
18
|
+
* @typedef {import("@jskit-ai/resource-runtime/server/types").ResourceHandle} CrudRepository
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* The CRUD service a CRUD feature provides as its capability's `service`: list,
|
|
23
|
+
* view, create, patch and delete, answering JSON:API documents.
|
|
24
|
+
* @typedef {ReturnType<typeof import("./jsonApiModule/service.js").createCrudService>} CrudService
|
|
17
25
|
*/
|
|
18
26
|
|
|
19
27
|
/**
|
|
@@ -39,12 +47,12 @@
|
|
|
39
47
|
*/
|
|
40
48
|
|
|
41
49
|
/**
|
|
42
|
-
* What a `
|
|
43
|
-
* application names: the
|
|
44
|
-
* decorateRepository and decorateService. The service keeps only the
|
|
45
|
-
* of the feature's enabled operations.
|
|
50
|
+
* What a `defineCrudFeature` feature provides under the capability its
|
|
51
|
+
* application names: the CRUD contract, its repository and its service, after
|
|
52
|
+
* any decorateRepository and decorateService. The service keeps only the
|
|
53
|
+
* methods of the feature's enabled operations.
|
|
46
54
|
* @typedef {object} CrudResourceApi
|
|
47
|
-
* @property {
|
|
55
|
+
* @property {CrudContract} crud
|
|
48
56
|
* @property {CrudRepository} repository
|
|
49
57
|
* @property {CrudService} service
|
|
50
58
|
*/
|
|
@@ -62,7 +70,7 @@
|
|
|
62
70
|
* @typedef {{
|
|
63
71
|
* input: any,
|
|
64
72
|
* context: object,
|
|
65
|
-
* resource:
|
|
73
|
+
* resource: CrudContract,
|
|
66
74
|
* repository: Repository,
|
|
67
75
|
* service: Service
|
|
68
76
|
* } & Requires} CrudCustomActionInvocation
|
|
@@ -71,8 +79,9 @@
|
|
|
71
79
|
/**
|
|
72
80
|
* What an `operationLifecycle` hook receives: the operation, the input its
|
|
73
81
|
* schema validated, the action context, the feature's resource, repository
|
|
74
|
-
* and service, and `
|
|
75
|
-
*
|
|
82
|
+
* and service, and `options`, the call options to pass to the repository:
|
|
83
|
+
* `{ context }`, and inside a create, update or delete the transaction they
|
|
84
|
+
* share (afterCommit, which runs after the commit, gets `{ context }`).
|
|
76
85
|
* `after` and `afterCommit` also receive the operation's `result` (the JSON:API
|
|
77
86
|
* document result; null for delete); `execute` receives `standard(nextInput)`,
|
|
78
87
|
* which runs the standard operation and returns its result.
|
|
@@ -84,10 +93,10 @@
|
|
|
84
93
|
* @property {"list" | "view" | "create" | "update" | "delete"} operation
|
|
85
94
|
* @property {any} input
|
|
86
95
|
* @property {object} context
|
|
87
|
-
* @property {
|
|
96
|
+
* @property {CrudContract} resource
|
|
88
97
|
* @property {Repository} repository
|
|
89
98
|
* @property {Service} service
|
|
90
|
-
* @property {import("@jskit-ai/
|
|
99
|
+
* @property {import("@jskit-ai/resource-runtime/server/types").ResourceCallOptions} options
|
|
91
100
|
* @property {CrudJsonApiResult | null} [result]
|
|
92
101
|
* @property {(nextInput?: object) => Promise<CrudJsonApiResult | null>} [standard]
|
|
93
102
|
*/
|
|
@@ -120,37 +129,4 @@
|
|
|
120
129
|
* @typedef {{ list?: CrudLifecycleHooks<Service, Repository>, view?: CrudLifecycleHooks<Service, Repository>, create?: CrudLifecycleHooks<Service, Repository>, update?: CrudLifecycleHooks<Service, Repository>, delete?: CrudLifecycleHooks<Service, Repository> }} CrudOperationLifecycle
|
|
121
130
|
*/
|
|
122
131
|
|
|
123
|
-
/**
|
|
124
|
-
* The records repository a CRUD service reads and writes through, as createCrudResourceRuntime builds it.
|
|
125
|
-
* @typedef {ReturnType<typeof import("./resourceRuntime/index.js").createCrudResourceRuntime>} CrudRecordRepository
|
|
126
|
-
*/
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* What a records repository resolves once from its resource and options, and each of its calls reads.
|
|
130
|
-
* @typedef {ReturnType<typeof import("./resourceRuntime/compiledRuntime.js").buildCompiledCrudRepositoryRuntime>} CompiledCrudRepositoryRuntime
|
|
131
|
-
*/
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* The repository a lookup reads: any object with listByIds().
|
|
135
|
-
* @typedef {object} CrudLookupRepository
|
|
136
|
-
* @property {(ids: unknown[], options?: Record<string, unknown>) => Promise<unknown>} listByIds
|
|
137
|
-
* @property {string} [ownershipFilter] The ownership filter its records use.
|
|
138
|
-
*/
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* A records service's field access policy: the fields a call may read and
|
|
142
|
-
* write (a list, a set, "*", or a function of the call that returns one), and
|
|
143
|
-
* whether a write to another field throws or is stripped.
|
|
144
|
-
* createFieldAccessForRoleMatrix builds one from a role matrix.
|
|
145
|
-
* @typedef {object} CrudFieldAccess
|
|
146
|
-
* @property {unknown} [readable]
|
|
147
|
-
* @property {unknown} [writable]
|
|
148
|
-
* @property {"throw" | "strip"} [writeMode]
|
|
149
|
-
*/
|
|
150
|
-
|
|
151
|
-
/**
|
|
152
|
-
* The resource, namespace and field access a CRUD service's methods share.
|
|
153
|
-
* @typedef {ReturnType<typeof import("./serviceMethods.js").createCrudServiceRuntime>} CrudServiceRuntime
|
|
154
|
-
*/
|
|
155
|
-
|
|
156
132
|
export {};
|
|
@@ -7,7 +7,8 @@ import {
|
|
|
7
7
|
validateSchemaPayload
|
|
8
8
|
} from "@jskit-ai/kernel/shared/validators";
|
|
9
9
|
import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
|
|
10
|
-
import {
|
|
10
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
11
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
11
12
|
import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
|
|
12
13
|
import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
|
|
13
14
|
|
|
@@ -45,37 +46,35 @@ function lookupField(namespace, relationshipName) {
|
|
|
45
46
|
namespace,
|
|
46
47
|
valueKey: "id",
|
|
47
48
|
labelKey: "name"
|
|
48
|
-
},
|
|
49
|
-
operations: {
|
|
50
|
-
output: { required: true }
|
|
51
49
|
}
|
|
52
50
|
};
|
|
53
51
|
}
|
|
54
52
|
|
|
55
53
|
function createBookingsResource() {
|
|
56
|
-
|
|
57
|
-
|
|
54
|
+
const bookings = defineTableResource({
|
|
55
|
+
name: "bookings",
|
|
58
56
|
tableName: "bookings",
|
|
59
|
-
|
|
60
|
-
contract: {
|
|
61
|
-
lookup: {
|
|
62
|
-
containerKey: "lookups"
|
|
63
|
-
}
|
|
64
|
-
},
|
|
57
|
+
ownership: "public",
|
|
65
58
|
schema: {
|
|
66
59
|
serviceId: lookupField("services", "service"),
|
|
67
60
|
productId: lookupField("products", "product"),
|
|
68
61
|
contactId: lookupField("contacts", "contact"),
|
|
69
62
|
petId: lookupField("pets", "pet"),
|
|
70
|
-
summary: {
|
|
71
|
-
type: "string",
|
|
72
|
-
required: true,
|
|
73
|
-
operations: {
|
|
74
|
-
output: { required: true }
|
|
75
|
-
}
|
|
76
|
-
}
|
|
63
|
+
summary: { type: "string", required: true }
|
|
77
64
|
}
|
|
78
65
|
});
|
|
66
|
+
return defineCrudContract(bookings, {
|
|
67
|
+
namespace: "bookings",
|
|
68
|
+
operations: ["list", "view"],
|
|
69
|
+
contract: {
|
|
70
|
+
lookup: {
|
|
71
|
+
containerKey: "lookups"
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
fields: Object.fromEntries(
|
|
75
|
+
["serviceId", "productId", "contactId", "petId", "summary"].map((field) => [field, { output: "required" }])
|
|
76
|
+
)
|
|
77
|
+
});
|
|
79
78
|
}
|
|
80
79
|
|
|
81
80
|
function selectFields(source, selectedFields = null) {
|
|
@@ -155,11 +154,11 @@ function createFixture() {
|
|
|
155
154
|
const resource = createBookingsResource();
|
|
156
155
|
const calls = [];
|
|
157
156
|
const service = {
|
|
158
|
-
async
|
|
157
|
+
async list(query, { context }) {
|
|
159
158
|
calls.push({ query, context });
|
|
160
159
|
return returnJsonApiDocument(createBookingDocument(query));
|
|
161
160
|
},
|
|
162
|
-
async
|
|
161
|
+
async view(_recordId, query) {
|
|
163
162
|
const document = createBookingDocument(query);
|
|
164
163
|
return returnJsonApiDocument({
|
|
165
164
|
data: document.data[0],
|