@jskit-ai/crud-core 0.2.3 → 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
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
cursorPaginationQueryValidator
|
|
4
4
|
} from "@jskit-ai/kernel/shared/validators";
|
|
5
5
|
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
6
|
-
import { resolveCrudParentFilterKeys
|
|
6
|
+
import { resolveCrudParentFilterKeys } from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
7
7
|
import { resolveJsonApiFieldsetContract } from "./jsonApiResourceContract.js";
|
|
8
8
|
|
|
9
9
|
const listSearchQueryValidator = Object.freeze({
|
|
@@ -24,8 +24,8 @@ const lookupIncludeQueryValidator = Object.freeze({
|
|
|
24
24
|
messages: {
|
|
25
25
|
default: {
|
|
26
26
|
code: "crud.query.includeInvalid",
|
|
27
|
-
message: "include expects a comma-separated string such as \"
|
|
28
|
-
params: { example: "
|
|
27
|
+
message: "include expects a comma-separated string such as \"author,publisher\".",
|
|
28
|
+
params: { example: "author,publisher" }
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
}
|
|
@@ -33,7 +33,7 @@ const lookupIncludeQueryValidator = Object.freeze({
|
|
|
33
33
|
mode: "patch"
|
|
34
34
|
});
|
|
35
35
|
|
|
36
|
-
function
|
|
36
|
+
function buildJsonApiFieldsetValueDefinition({ allowedFields = [] } = {}) {
|
|
37
37
|
const normalizedAllowedFields = [...new Set(
|
|
38
38
|
(Array.isArray(allowedFields) ? allowedFields : [])
|
|
39
39
|
.map((entry) => normalizeText(entry))
|
|
@@ -53,7 +53,7 @@ function createJsonApiFieldsetValueDefinition({ allowedFields = [] } = {}) {
|
|
|
53
53
|
});
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
const jsonApiFieldsetValueDefinition =
|
|
56
|
+
const jsonApiFieldsetValueDefinition = buildJsonApiFieldsetValueDefinition();
|
|
57
57
|
|
|
58
58
|
const jsonApiFieldsetsQueryValidator = Object.freeze({
|
|
59
59
|
schema: createSchema({
|
|
@@ -63,8 +63,8 @@ const jsonApiFieldsetsQueryValidator = Object.freeze({
|
|
|
63
63
|
messages: {
|
|
64
64
|
default: {
|
|
65
65
|
code: "crud.query.fieldsInvalid",
|
|
66
|
-
message: "fields expects an object such as {\"
|
|
67
|
-
params: { example: "{\"
|
|
66
|
+
message: "fields expects an object such as {\"books\":[\"authorId\"],\"authors\":[\"name\"]}.",
|
|
67
|
+
params: { example: "{\"books\":[\"authorId\"],\"authors\":[\"name\"]}" }
|
|
68
68
|
}
|
|
69
69
|
},
|
|
70
70
|
values: jsonApiFieldsetValueDefinition
|
|
@@ -104,7 +104,7 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
104
104
|
Object.fromEntries(
|
|
105
105
|
contract.resourceTypes.map((resourceType) => [
|
|
106
106
|
resourceType,
|
|
107
|
-
|
|
107
|
+
buildJsonApiFieldsetValueDefinition({
|
|
108
108
|
allowedFields: resourceType === contract.primaryType ? contract.primaryFields : []
|
|
109
109
|
})
|
|
110
110
|
])
|
|
@@ -132,9 +132,9 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
132
132
|
}
|
|
133
133
|
|
|
134
134
|
function resolveCrudListUsesOrderedCursor(list = {}) {
|
|
135
|
-
const entries = Array.isArray(list
|
|
135
|
+
const entries = Array.isArray(list.orderBy)
|
|
136
136
|
? list.orderBy
|
|
137
|
-
: list
|
|
137
|
+
: list.orderBy == null
|
|
138
138
|
? []
|
|
139
139
|
: [list.orderBy];
|
|
140
140
|
|
|
@@ -173,10 +173,6 @@ function createCrudCursorPaginationQueryValidator(list = {}) {
|
|
|
173
173
|
});
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
-
function resolveCrudParentFilterKeys(resource = {}) {
|
|
177
|
-
return resolveSharedCrudParentFilterKeys(resource);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
176
|
function createCrudParentFilterQueryValidator(resource = {}) {
|
|
181
177
|
const keys = resolveCrudParentFilterKeys(resource);
|
|
182
178
|
const schemaProperties = {};
|
|
@@ -194,7 +190,17 @@ function createCrudParentFilterQueryValidator(resource = {}) {
|
|
|
194
190
|
});
|
|
195
191
|
}
|
|
196
192
|
|
|
193
|
+
/**
|
|
194
|
+
* The query schemas of a CRUD list: cursor, search, parent filters, list filters, include and fieldsets.
|
|
195
|
+
* @param {object} [options]
|
|
196
|
+
* @param {object} [options.resource]
|
|
197
|
+
* @param {object | null} [options.listFilterQueryValidator]
|
|
198
|
+
* @param {object} [options.searchQueryValidator]
|
|
199
|
+
* @param {object} [options.includeQueryValidator]
|
|
200
|
+
* @param {object} [options.fieldsetsQueryValidator]
|
|
201
|
+
*/
|
|
197
202
|
function createStandardCrudListQueryValidators({
|
|
203
|
+
// readable-check: allow dependency-default - data: a resource definition
|
|
198
204
|
resource = {},
|
|
199
205
|
listFilterQueryValidator = null,
|
|
200
206
|
searchQueryValidator = listSearchQueryValidator,
|
|
@@ -203,12 +209,12 @@ function createStandardCrudListQueryValidators({
|
|
|
203
209
|
} = {}) {
|
|
204
210
|
const resolvedListFilterQueryValidator =
|
|
205
211
|
listFilterQueryValidator
|
|
206
|
-
?? resource
|
|
212
|
+
?? resource.contract?.listFilters?.queryValidator
|
|
207
213
|
?? null;
|
|
208
214
|
|
|
209
|
-
return [
|
|
215
|
+
return Object.freeze([
|
|
210
216
|
createCrudCursorPaginationQueryValidator({
|
|
211
|
-
orderBy: resource
|
|
217
|
+
orderBy: resource.defaultSort
|
|
212
218
|
}),
|
|
213
219
|
searchQueryValidator,
|
|
214
220
|
createCrudParentFilterQueryValidator(resource),
|
|
@@ -217,17 +223,17 @@ function createStandardCrudListQueryValidators({
|
|
|
217
223
|
: []),
|
|
218
224
|
includeQueryValidator,
|
|
219
225
|
fieldsetsQueryValidator
|
|
220
|
-
];
|
|
226
|
+
]);
|
|
221
227
|
}
|
|
222
228
|
|
|
223
229
|
function createStandardCrudViewQueryValidators({
|
|
224
230
|
includeQueryValidator = lookupIncludeQueryValidator,
|
|
225
231
|
fieldsetsQueryValidator = jsonApiFieldsetsQueryValidator
|
|
226
232
|
} = {}) {
|
|
227
|
-
return [
|
|
233
|
+
return Object.freeze([
|
|
228
234
|
includeQueryValidator,
|
|
229
235
|
fieldsetsQueryValidator
|
|
230
|
-
];
|
|
236
|
+
]);
|
|
231
237
|
}
|
|
232
238
|
|
|
233
239
|
export {
|
|
@@ -236,7 +242,6 @@ export {
|
|
|
236
242
|
listSearchQueryValidator,
|
|
237
243
|
lookupIncludeQueryValidator,
|
|
238
244
|
jsonApiFieldsetsQueryValidator,
|
|
239
|
-
resolveCrudParentFilterKeys,
|
|
240
245
|
createCrudParentFilterQueryValidator,
|
|
241
246
|
createStandardCrudListQueryValidators,
|
|
242
247
|
createStandardCrudViewQueryValidators
|
|
@@ -1,9 +1,35 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
normalizeCrudLookupNamespace
|
|
4
|
-
} from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
1
|
+
import { normalizeCrudLookupNamespace } from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
2
|
+
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
5
3
|
import { toSnakeCase } from "@jskit-ai/kernel/shared/support/stringCase";
|
|
6
4
|
|
|
5
|
+
const LOOKUP_OWNERSHIP_FILTER_VALUES = Object.freeze([
|
|
6
|
+
"public",
|
|
7
|
+
"user",
|
|
8
|
+
"workspace",
|
|
9
|
+
"workspace_user"
|
|
10
|
+
]);
|
|
11
|
+
const LOOKUP_OWNERSHIP_FILTER_SET = new Set(LOOKUP_OWNERSHIP_FILTER_VALUES);
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The ownership filter a lookup's records use, or "" when it names none.
|
|
15
|
+
* @param {unknown} value
|
|
16
|
+
* @param {{ context: string }} labels The name its error gives the value.
|
|
17
|
+
*/
|
|
18
|
+
function normalizeLookupOwnershipFilter(value, { context }) {
|
|
19
|
+
const normalized = normalizeText(value).toLowerCase();
|
|
20
|
+
if (!normalized) {
|
|
21
|
+
return "";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
if (LOOKUP_OWNERSHIP_FILTER_SET.has(normalized)) {
|
|
25
|
+
return normalized;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
throw new TypeError(
|
|
29
|
+
`${context} must be one of: ${LOOKUP_OWNERSHIP_FILTER_VALUES.join(", ")}.`
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
|
|
7
33
|
function requireCrudLookupNamespace(value = "", { context = "crudLookup" } = {}) {
|
|
8
34
|
const normalizedNamespace = normalizeCrudLookupNamespace(value);
|
|
9
35
|
if (!normalizedNamespace) {
|
|
@@ -25,21 +51,8 @@ function resolveCrudLookupToken(namespace = "", { context = "crudLookup" } = {})
|
|
|
25
51
|
return `lookup.${tokenPart}`;
|
|
26
52
|
}
|
|
27
53
|
|
|
28
|
-
function resolveCrudLookupNamespaceFromRelation(relation = {}, { context = "crudLookup" } = {}) {
|
|
29
|
-
const normalizedNamespace =
|
|
30
|
-
normalizeCrudLookupNamespace(relation?.namespace) ||
|
|
31
|
-
normalizeCrudLookupNamespace(relation?.apiPath);
|
|
32
|
-
if (!normalizedNamespace) {
|
|
33
|
-
throw new Error(`${context} requires relation.namespace.`);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
return normalizedNamespace;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
54
|
export {
|
|
40
|
-
|
|
41
|
-
normalizeCrudLookupNamespace,
|
|
55
|
+
normalizeLookupOwnershipFilter,
|
|
42
56
|
requireCrudLookupNamespace,
|
|
43
|
-
resolveCrudLookupNamespaceFromRelation,
|
|
44
57
|
resolveCrudLookupToken
|
|
45
58
|
};
|
package/src/server/lookups.js
CHANGED
|
@@ -1,50 +1,36 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
const LOOKUP_OWNERSHIP_FILTER_SET = new Set(LOOKUP_OWNERSHIP_FILTER_VALUES);
|
|
11
|
-
|
|
12
|
-
function normalizeLookupOwnershipFilter(value, { context = "crudLookup ownershipFilter" } = {}) {
|
|
13
|
-
const normalized = normalizeText(value).toLowerCase();
|
|
14
|
-
if (!normalized) {
|
|
15
|
-
return "";
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
if (LOOKUP_OWNERSHIP_FILTER_SET.has(normalized)) {
|
|
19
|
-
return normalized;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
throw new TypeError(
|
|
23
|
-
`${context} must be one of: ${LOOKUP_OWNERSHIP_FILTER_VALUES.join(", ")}.`
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
|
|
1
|
+
import { normalizeLookupOwnershipFilter, resolveCrudLookupToken } from "./lookupPathSupport.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A lookup over a repository's listByIds(), which includes no relationships unless asked.
|
|
5
|
+
* @param {import("./types.js").CrudLookupRepository} repository
|
|
6
|
+
* @param {object} [options]
|
|
7
|
+
* @param {string} [options.context] The name the lookup's errors give it.
|
|
8
|
+
* @param {string} [options.ownershipFilter] Defaults to the repository's.
|
|
9
|
+
*/
|
|
27
10
|
function createCrudLookup(repository, { context = "crudLookup", ownershipFilter = "" } = {}) {
|
|
11
|
+
// readable-check: allow method-probe - input validation: the application passes its own repository
|
|
28
12
|
if (!repository || typeof repository.listByIds !== "function") {
|
|
29
13
|
throw new Error(`${context} requires repository.listByIds(ids, options).`);
|
|
30
14
|
}
|
|
31
15
|
|
|
32
16
|
const normalizedOwnershipFilter = normalizeLookupOwnershipFilter(
|
|
33
|
-
ownershipFilter || repository
|
|
17
|
+
ownershipFilter || repository.ownershipFilter,
|
|
34
18
|
{
|
|
35
19
|
context: `${context} ownershipFilter`
|
|
36
20
|
}
|
|
37
21
|
);
|
|
38
22
|
|
|
23
|
+
async function listByIds(ids = [], options = {}) {
|
|
24
|
+
const include = options.include === undefined ? "none" : options.include;
|
|
25
|
+
return repository.listByIds(ids, {
|
|
26
|
+
...options,
|
|
27
|
+
include
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
39
31
|
return Object.freeze({
|
|
40
32
|
ownershipFilter: normalizedOwnershipFilter || null,
|
|
41
|
-
|
|
42
|
-
const include = options?.include === undefined ? "none" : options.include;
|
|
43
|
-
return repository.listByIds(ids, {
|
|
44
|
-
...options,
|
|
45
|
-
include
|
|
46
|
-
});
|
|
47
|
-
}
|
|
33
|
+
listByIds
|
|
48
34
|
});
|
|
49
35
|
}
|
|
50
36
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text without surrounding spaces, or null when there is none.
|
|
3
|
+
* @param {unknown} value
|
|
4
|
+
*/
|
|
5
|
+
function normalizeOptionalText(value) {
|
|
6
|
+
if (value == null) {
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
const normalized = String(value).trim();
|
|
10
|
+
return normalized || null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export { normalizeOptionalText };
|
|
@@ -81,7 +81,7 @@ function resolveColumnName(fieldKey, overrides = {}) {
|
|
|
81
81
|
return "";
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
const overrideValue = String(overrides
|
|
84
|
+
const overrideValue = String(overrides[normalizedKey] || "").trim();
|
|
85
85
|
if (overrideValue) {
|
|
86
86
|
return overrideValue;
|
|
87
87
|
}
|
|
@@ -103,7 +103,7 @@ function buildRepositoryColumnMetadata({
|
|
|
103
103
|
.filter(Boolean);
|
|
104
104
|
|
|
105
105
|
const deriveMapping = (key) => {
|
|
106
|
-
if (fieldStorageByKey
|
|
106
|
+
if (fieldStorageByKey[key] !== CRUD_FIELD_STORAGE_COLUMN) {
|
|
107
107
|
return null;
|
|
108
108
|
}
|
|
109
109
|
const column = resolveColumnName(key, columnOverrides);
|
|
@@ -156,7 +156,7 @@ function requireFieldDefinitions(definition, {
|
|
|
156
156
|
return properties;
|
|
157
157
|
}
|
|
158
158
|
|
|
159
|
-
function resolveFieldDefinitionType(definition
|
|
159
|
+
function resolveFieldDefinitionType(definition) {
|
|
160
160
|
return normalizeText(definition?.type).toLowerCase();
|
|
161
161
|
}
|
|
162
162
|
|
|
@@ -174,7 +174,7 @@ function definitionIncludesRecordIdType(definition = {}) {
|
|
|
174
174
|
return true;
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
-
return type === "string" && normalizeText(definition
|
|
177
|
+
return type === "string" && normalizeText(definition.pattern) === RECORD_ID_PATTERN;
|
|
178
178
|
}
|
|
179
179
|
|
|
180
180
|
function deriveRepositoryMappingFromResource(resource = {}, { context = "crudRepository" } = {}) {
|
|
@@ -187,17 +187,17 @@ function deriveRepositoryMappingFromResource(resource = {}, { context = "crudRep
|
|
|
187
187
|
throw new TypeError(`${context} requires resource.operations.`);
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
-
const outputProperties = requireFieldDefinitions(operations
|
|
190
|
+
const outputProperties = requireFieldDefinitions(operations.view?.output, {
|
|
191
191
|
context,
|
|
192
192
|
schemaLabel: "operations.view.output",
|
|
193
193
|
defaultMode: "replace"
|
|
194
194
|
});
|
|
195
|
-
const writeProperties = requireFieldDefinitions(operations
|
|
195
|
+
const writeProperties = requireFieldDefinitions(operations.create?.body, {
|
|
196
196
|
context,
|
|
197
197
|
schemaLabel: "operations.create.body",
|
|
198
198
|
defaultMode: "create"
|
|
199
199
|
});
|
|
200
|
-
const patchProperties = resolveOptionalFieldDefinitions(operations
|
|
200
|
+
const patchProperties = resolveOptionalFieldDefinitions(operations.patch?.body, {
|
|
201
201
|
context,
|
|
202
202
|
schemaLabel: "operations.patch.body",
|
|
203
203
|
defaultMode: "patch"
|
|
@@ -225,11 +225,11 @@ function deriveRepositoryMappingFromResource(resource = {}, { context = "crudRep
|
|
|
225
225
|
if (!key) {
|
|
226
226
|
continue;
|
|
227
227
|
}
|
|
228
|
-
fieldStorageByKey[key] = entry
|
|
229
|
-
if (entry
|
|
228
|
+
fieldStorageByKey[key] = entry.storage.mode || CRUD_FIELD_STORAGE_COLUMN;
|
|
229
|
+
if (entry.storage.column) {
|
|
230
230
|
columnOverrides[key] = entry.storage.column;
|
|
231
231
|
}
|
|
232
|
-
if (entry
|
|
232
|
+
if (entry.storage.writeSerializer) {
|
|
233
233
|
writeSerializerByKey[key] = entry.storage.writeSerializer;
|
|
234
234
|
}
|
|
235
235
|
}
|
|
@@ -408,6 +408,7 @@ function applyCrudListQueryFilters(
|
|
|
408
408
|
parentFilterColumns = {}
|
|
409
409
|
} = {}
|
|
410
410
|
) {
|
|
411
|
+
// readable-check: allow method-probe - safety invariant: a value that is not a query builder fails inside the filter callbacks with an unclear error
|
|
411
412
|
if (!query || typeof query.modify !== "function" || typeof query.where !== "function") {
|
|
412
413
|
throw new TypeError("applyCrudListQueryFilters requires query builder.");
|
|
413
414
|
}
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
2
|
+
import {
|
|
3
|
+
buildRepositoryColumnMetadata,
|
|
4
|
+
deriveRepositoryMappingFromResource,
|
|
5
|
+
requireCrudTableName,
|
|
6
|
+
resolveColumnName,
|
|
7
|
+
resolveCrudIdColumn
|
|
8
|
+
} from "../repositorySupport.js";
|
|
9
|
+
import { resolveSchemaTransportSchemaDefinition } from "@jskit-ai/kernel/shared/validators";
|
|
10
|
+
import { buildCrudLookupRuntime } from "./lookupHydration.js";
|
|
11
|
+
import { CRUD_FIELD_STORAGE_COLUMN } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
|
|
12
|
+
import { resolveListRuntimeConfig } from "./listControls.js";
|
|
13
|
+
|
|
14
|
+
const REPOSITORY_OPERATION_KEYS = Object.freeze([
|
|
15
|
+
"read",
|
|
16
|
+
"list",
|
|
17
|
+
"findById",
|
|
18
|
+
"listByIds",
|
|
19
|
+
"create",
|
|
20
|
+
"updateById",
|
|
21
|
+
"deleteById"
|
|
22
|
+
]);
|
|
23
|
+
const REPOSITORY_OPERATION_STAGE_KEYS = Object.freeze({
|
|
24
|
+
read: ["applyQuery"],
|
|
25
|
+
list: ["applyQuery"],
|
|
26
|
+
findById: ["applyQuery"],
|
|
27
|
+
listByIds: ["applyQuery"],
|
|
28
|
+
create: ["preparePayload", "prepareInsertPayload", "applyQuery"],
|
|
29
|
+
updateById: ["preparePatch", "applyQuery"],
|
|
30
|
+
deleteById: ["applyQuery"]
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
function requireCrudRepositoryOptions(value) {
|
|
34
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
35
|
+
throw new TypeError("createCrudResourceRuntime requires repository options object when provided.");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function resolveRepositoryDefaults(resource, repositoryMapping, { context }) {
|
|
42
|
+
const resourceName = normalizeText(resource.namespace);
|
|
43
|
+
const tableName = normalizeText(resource.tableName) || resourceName;
|
|
44
|
+
if (!tableName) {
|
|
45
|
+
throw new TypeError(`${context} requires resource.tableName or resource.namespace.`);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const idColumn = normalizeText(resource.idColumn) || resolveColumnName("id", repositoryMapping.columnOverrides) || "id";
|
|
49
|
+
const createdAtColumn = repositoryMapping.outputKeys.includes("createdAt") &&
|
|
50
|
+
repositoryMapping.fieldStorageByKey.createdAt === CRUD_FIELD_STORAGE_COLUMN
|
|
51
|
+
? resolveColumnName("createdAt", repositoryMapping.columnOverrides)
|
|
52
|
+
: "";
|
|
53
|
+
const updatedAtColumn = repositoryMapping.outputKeys.includes("updatedAt") &&
|
|
54
|
+
repositoryMapping.fieldStorageByKey.updatedAt === CRUD_FIELD_STORAGE_COLUMN
|
|
55
|
+
? resolveColumnName("updatedAt", repositoryMapping.columnOverrides)
|
|
56
|
+
: "";
|
|
57
|
+
|
|
58
|
+
return Object.freeze({
|
|
59
|
+
tableName,
|
|
60
|
+
idColumn,
|
|
61
|
+
createdAtColumn,
|
|
62
|
+
updatedAtColumn
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function normalizeCrudVirtualFieldHandlers(virtualFields = {}, repositoryMapping, { context }) {
|
|
67
|
+
const expectedKeys = new Set(repositoryMapping.virtualOutputKeys);
|
|
68
|
+
if (expectedKeys.size < 1) {
|
|
69
|
+
if (virtualFields === null) {
|
|
70
|
+
return Object.freeze([]);
|
|
71
|
+
}
|
|
72
|
+
if (!virtualFields || typeof virtualFields !== "object" || Array.isArray(virtualFields)) {
|
|
73
|
+
throw new TypeError(`${context} virtualFields must be an object when provided.`);
|
|
74
|
+
}
|
|
75
|
+
if (Object.keys(virtualFields).length > 0) {
|
|
76
|
+
throw new Error(
|
|
77
|
+
`${context} virtualFields contains registrations, but the resource does not declare any storage.virtual fields.`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
return Object.freeze([]);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (!virtualFields || typeof virtualFields !== "object" || Array.isArray(virtualFields)) {
|
|
84
|
+
throw new TypeError(`${context} virtualFields must be an object.`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const normalizedHandlers = [];
|
|
88
|
+
const seenKeys = new Set();
|
|
89
|
+
for (const [rawKey, handlerConfig] of Object.entries(virtualFields)) {
|
|
90
|
+
const key = normalizeText(rawKey);
|
|
91
|
+
if (!key || seenKeys.has(key)) {
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (!expectedKeys.has(key)) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`${context} virtualFields["${key}"] is unknown; declare the field in the resource schema with storage.virtual true.`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
if (!handlerConfig || typeof handlerConfig !== "object" || Array.isArray(handlerConfig)) {
|
|
100
|
+
throw new TypeError(`${context} virtualFields["${key}"] must be an object.`);
|
|
101
|
+
}
|
|
102
|
+
// readable-check: allow method-probe - input validation: an application's virtual field handler must have applyProjection()
|
|
103
|
+
if (typeof handlerConfig.applyProjection !== "function") {
|
|
104
|
+
throw new TypeError(`${context} virtualFields["${key}"].applyProjection must be a function.`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
seenKeys.add(key);
|
|
108
|
+
normalizedHandlers.push(Object.freeze({
|
|
109
|
+
key,
|
|
110
|
+
alias: resolveColumnName(key, repositoryMapping.columnOverrides),
|
|
111
|
+
applyProjection: handlerConfig.applyProjection
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
for (const key of expectedKeys) {
|
|
116
|
+
if (!seenKeys.has(key)) {
|
|
117
|
+
throw new Error(
|
|
118
|
+
`${context} resource output field "${key}" is virtual but no repository runtime projection was registered.`
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return Object.freeze(normalizedHandlers);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function resolveRecordOutputValidator(resource, { context }) {
|
|
127
|
+
const output = resource.operations.view?.output;
|
|
128
|
+
if (!output || typeof output !== "object" || Array.isArray(output)) {
|
|
129
|
+
throw new TypeError(`${context} requires operations.view.output.`);
|
|
130
|
+
}
|
|
131
|
+
const schema = resolveSchemaTransportSchemaDefinition(output, {
|
|
132
|
+
context: `${context} operations.view.output`,
|
|
133
|
+
defaultMode: "replace"
|
|
134
|
+
});
|
|
135
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
136
|
+
throw new TypeError(`${context} requires operations.view.output to resolve to an object schema.`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return output;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function resolveOperationBodyValidator(resource, operationKey, { context }) {
|
|
143
|
+
const body = resource.operations[operationKey]?.body;
|
|
144
|
+
if (body == null) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) {
|
|
148
|
+
throw new TypeError(`${context} operations.${operationKey}.body must be an object when provided.`);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return body;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function normalizeCrudRepositoryOperationStage(stage, stageLabel, { context }) {
|
|
155
|
+
if (stage === undefined || stage === null) {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
if (typeof stage !== "function") {
|
|
159
|
+
throw new TypeError(`${context} ${stageLabel} must be a function when provided.`);
|
|
160
|
+
}
|
|
161
|
+
return stage;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function normalizeCrudRepositoryOperationConfig(config, operationKey, { context }) {
|
|
165
|
+
if (config === undefined || config === null) {
|
|
166
|
+
return Object.freeze({});
|
|
167
|
+
}
|
|
168
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
169
|
+
throw new TypeError(`${context} operations.${operationKey} must be an object when provided.`);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const allowedKeys = REPOSITORY_OPERATION_STAGE_KEYS[operationKey];
|
|
173
|
+
const normalized = {};
|
|
174
|
+
for (const [rawKey, rawValue] of Object.entries(config)) {
|
|
175
|
+
const key = normalizeText(rawKey);
|
|
176
|
+
if (!key) {
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
if (!allowedKeys.includes(key)) {
|
|
180
|
+
throw new TypeError(
|
|
181
|
+
`${context} operations.${operationKey}.${key} is not supported. Allowed keys: ${allowedKeys.join(", ")}.`
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
normalized[key] = normalizeCrudRepositoryOperationStage(
|
|
185
|
+
rawValue,
|
|
186
|
+
`operations.${operationKey}.${key}`,
|
|
187
|
+
{ context }
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return Object.freeze(normalized);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Each repository operation's stages, with an entry for every operation, so a
|
|
196
|
+
* stage is read as `operations.<operation>.<stage>` (undefined when not configured).
|
|
197
|
+
* @param {unknown} sourceOperations The repository options' operations, when given.
|
|
198
|
+
* @param {{ context: string }} labels
|
|
199
|
+
*/
|
|
200
|
+
function normalizeCrudRepositoryOperations(sourceOperations, { context }) {
|
|
201
|
+
const source = sourceOperations ?? {};
|
|
202
|
+
if (typeof source !== "object" || Array.isArray(source)) {
|
|
203
|
+
throw new TypeError(`${context} operations must be an object when provided.`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const normalized = {};
|
|
207
|
+
for (const operationKey of REPOSITORY_OPERATION_KEYS) {
|
|
208
|
+
normalized[operationKey] = normalizeCrudRepositoryOperationConfig(
|
|
209
|
+
source[operationKey],
|
|
210
|
+
operationKey,
|
|
211
|
+
{ context }
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
for (const rawKey of Object.keys(source)) {
|
|
216
|
+
const key = normalizeText(rawKey);
|
|
217
|
+
if (key && !REPOSITORY_OPERATION_KEYS.includes(key)) {
|
|
218
|
+
throw new TypeError(
|
|
219
|
+
`${context} operations.${key} is not supported. Allowed keys: ${REPOSITORY_OPERATION_KEYS.join(", ")}.`
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return Object.freeze(normalized);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* What a records repository resolves once from its resource and options: the
|
|
229
|
+
* error context, table and id column (the options' tableName and idColumn, else
|
|
230
|
+
* the resource's), the field mapping, the input and output schemas, the list
|
|
231
|
+
* controls, the lookups, each operation's stages and the virtual fields.
|
|
232
|
+
* @param {import("../types.js").CrudResourceDefinition} resource
|
|
233
|
+
* @param {object} repositoryOptions
|
|
234
|
+
*/
|
|
235
|
+
function buildCompiledCrudRepositoryRuntime(resource, repositoryOptions) {
|
|
236
|
+
const sourceOptions = requireCrudRepositoryOptions(repositoryOptions);
|
|
237
|
+
const context = normalizeText(sourceOptions.context) || "crudRepository";
|
|
238
|
+
const repositoryMapping = deriveRepositoryMappingFromResource(resource, { context });
|
|
239
|
+
const defaults = resolveRepositoryDefaults(resource, repositoryMapping, { context });
|
|
240
|
+
const output = resolveRecordOutputValidator(resource, { context });
|
|
241
|
+
const lookupRuntime = buildCrudLookupRuntime(resource, {
|
|
242
|
+
outputKeys: repositoryMapping.outputKeys,
|
|
243
|
+
context
|
|
244
|
+
});
|
|
245
|
+
const listRuntime = resolveListRuntimeConfig(sourceOptions.list, repositoryMapping.listSearchColumns, {
|
|
246
|
+
idColumn: defaults.idColumn
|
|
247
|
+
});
|
|
248
|
+
const { selectColumns } = buildRepositoryColumnMetadata({
|
|
249
|
+
outputKeys: repositoryMapping.columnBackedOutputKeys,
|
|
250
|
+
writeKeys: repositoryMapping.writeKeys,
|
|
251
|
+
columnOverrides: repositoryMapping.columnOverrides,
|
|
252
|
+
fieldStorageByKey: repositoryMapping.fieldStorageByKey
|
|
253
|
+
});
|
|
254
|
+
const normalizedSelectColumns = Object.freeze(
|
|
255
|
+
[...new Set([
|
|
256
|
+
...selectColumns,
|
|
257
|
+
...listRuntime.orderBy.map(({ column }) => column)
|
|
258
|
+
])]
|
|
259
|
+
);
|
|
260
|
+
|
|
261
|
+
return Object.freeze({
|
|
262
|
+
context,
|
|
263
|
+
resource,
|
|
264
|
+
repositoryOptions: sourceOptions,
|
|
265
|
+
tableName: requireCrudTableName(sourceOptions.tableName ?? defaults.tableName, { context }),
|
|
266
|
+
idColumn: resolveCrudIdColumn(sourceOptions.idColumn, { fallback: defaults.idColumn }),
|
|
267
|
+
defaults,
|
|
268
|
+
input: Object.freeze({
|
|
269
|
+
create: resolveOperationBodyValidator(resource, "create", { context }),
|
|
270
|
+
patch: resolveOperationBodyValidator(resource, "patch", { context })
|
|
271
|
+
}),
|
|
272
|
+
selectColumns: normalizedSelectColumns,
|
|
273
|
+
output,
|
|
274
|
+
list: listRuntime,
|
|
275
|
+
lookup: lookupRuntime,
|
|
276
|
+
mapping: repositoryMapping,
|
|
277
|
+
operations: normalizeCrudRepositoryOperations(sourceOptions.operations, { context }),
|
|
278
|
+
virtualFields: normalizeCrudVirtualFieldHandlers(sourceOptions.virtualFields, repositoryMapping, { context })
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export {
|
|
283
|
+
buildCompiledCrudRepositoryRuntime
|
|
284
|
+
};
|