@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,355 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
buildJsonRestQueryParams,
|
|
3
|
-
createJsonRestContext,
|
|
4
|
-
queryAllJsonRestCollectionDocument,
|
|
5
|
-
returnBadRequestWhenJsonRestFieldsetInvalid,
|
|
6
|
-
returnNullWhenJsonRestResourceMissing
|
|
7
|
-
} from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
|
|
8
|
-
import { resolveTransaction, retryDeadlocks } from "@jskit-ai/database-runtime/shared";
|
|
9
|
-
import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
10
|
-
|
|
11
|
-
/** @typedef {"full" | "minimal" | "none"} WriteReturning */
|
|
12
|
-
|
|
13
|
-
const WRITE_RETURNING = new Set(["full", "minimal", "none"]);
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* @param {{ returning?: unknown }} options
|
|
17
|
-
* @param {WriteReturning} [fallback]
|
|
18
|
-
* @returns {WriteReturning}
|
|
19
|
-
*/
|
|
20
|
-
function writeReturning(options, fallback = "full") {
|
|
21
|
-
const returning = options.returning ?? fallback;
|
|
22
|
-
if (!WRITE_RETURNING.has(returning)) {
|
|
23
|
-
throw new TypeError(`returning must be "full", "minimal" or "none". Received: ${JSON.stringify(returning)}`);
|
|
24
|
-
}
|
|
25
|
-
return /** @type {WriteReturning} */ (returning);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* @param {object} dependencies
|
|
30
|
-
* @param {import("@jskit-ai/json-rest-api-core/server/types").RuntimeJsonRestApi} dependencies.api
|
|
31
|
-
* @param {import("../types.js").CrudResourceDefinition} dependencies.resource
|
|
32
|
-
* @param {string} dependencies.resourceScopeName
|
|
33
|
-
*/
|
|
34
|
-
function createCrudJsonApiRepository({ api, resource, resourceScopeName }) {
|
|
35
|
-
if (!resource || typeof resource !== "object" || Array.isArray(resource)) {
|
|
36
|
-
throw new TypeError("createCrudJsonApiRepository requires resource.");
|
|
37
|
-
}
|
|
38
|
-
const scopeName = String(resourceScopeName || "").trim();
|
|
39
|
-
if (!scopeName) {
|
|
40
|
-
throw new TypeError("createCrudJsonApiRepository requires resourceScopeName.");
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function withTransaction(work) {
|
|
44
|
-
return retryDeadlocks(() => api.transaction(work));
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
// A write given no transaction owns one, so it is outermost and may re-run.
|
|
48
|
-
function write(options, run) {
|
|
49
|
-
return resolveTransaction(options) ? run() : retryDeadlocks(run);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function inputData(payload) {
|
|
53
|
-
const data = { ...payload };
|
|
54
|
-
for (const [fieldName, definition] of Object.entries(resource.schema || {})) {
|
|
55
|
-
if (!definition?.belongsTo || !Object.hasOwn(data, fieldName)) {
|
|
56
|
-
continue;
|
|
57
|
-
}
|
|
58
|
-
const relationshipName = definition.as || fieldName;
|
|
59
|
-
if (relationshipName === fieldName) {
|
|
60
|
-
continue;
|
|
61
|
-
}
|
|
62
|
-
if (Object.hasOwn(data, relationshipName)) {
|
|
63
|
-
throw new TypeError(`Provide either "${fieldName}" or "${relationshipName}", not both.`);
|
|
64
|
-
}
|
|
65
|
-
if (data[fieldName] !== undefined) {
|
|
66
|
-
data[relationshipName] = data[fieldName];
|
|
67
|
-
}
|
|
68
|
-
delete data[fieldName];
|
|
69
|
-
}
|
|
70
|
-
return data;
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
function requireApiResource() {
|
|
74
|
-
const apiResource = api.resources[scopeName];
|
|
75
|
-
if (!apiResource) {
|
|
76
|
-
throw new Error(`JSON REST resource "${scopeName}" is not registered.`);
|
|
77
|
-
}
|
|
78
|
-
return apiResource;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** The largest `limit` queryDocuments accepts: the resource's json-rest-api `queryMaxLimit`. */
|
|
82
|
-
function queryMaxLimit() {
|
|
83
|
-
return requireApiResource().vars.queryMaxLimit;
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* One page of the records the query matches: `limit` records (the
|
|
88
|
-
* resource's default page without one) after `cursor`, with
|
|
89
|
-
* `meta.pagination` reporting `hasMore` and the next cursor. A `limit`
|
|
90
|
-
* above queryMaxLimit() throws a TypeError naming queryEveryDocument,
|
|
91
|
-
* because json-rest-api would answer only queryMaxLimit() records.
|
|
92
|
-
* @param {Record<string, unknown>} [query]
|
|
93
|
-
* @param {{ trx?: any, context?: object | null }} [options]
|
|
94
|
-
*/
|
|
95
|
-
async function queryDocuments(query = {}, options = {}) {
|
|
96
|
-
if (query.limit != null && Number(query.limit) > queryMaxLimit()) {
|
|
97
|
-
throw new TypeError(
|
|
98
|
-
`${scopeName} queryDocuments limit ${query.limit} is above its queryMaxLimit (${queryMaxLimit()}), so it would ` +
|
|
99
|
-
`return only ${queryMaxLimit()} records. Read every record with queryEveryDocument(query, options), or page with limit and cursor.`
|
|
100
|
-
);
|
|
101
|
-
}
|
|
102
|
-
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
103
|
-
requireApiResource().query(
|
|
104
|
-
{
|
|
105
|
-
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
106
|
-
transaction: resolveTransaction(options),
|
|
107
|
-
format: "jsonapi"
|
|
108
|
-
},
|
|
109
|
-
createJsonRestContext(options.context)
|
|
110
|
-
)
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Every record the query matches, as one JSON:API document `{ data,
|
|
116
|
-
* included }`, for server code that needs them all. It takes
|
|
117
|
-
* queryDocuments' filters, include and fields, but no limit, cursor or
|
|
118
|
-
* sort: it reads 1,000-record pages in id order in the caller's transaction,
|
|
119
|
-
* so no record is skipped or repeated. Sort the records it returns.
|
|
120
|
-
* @param {Record<string, unknown>} [query]
|
|
121
|
-
* @param {{ trx?: any, context?: object | null }} [options]
|
|
122
|
-
*/
|
|
123
|
-
async function queryEveryDocument(query = {}, options = {}) {
|
|
124
|
-
for (const key of ["limit", "cursor", "sort"]) {
|
|
125
|
-
if (query[key] != null) {
|
|
126
|
-
throw new TypeError(
|
|
127
|
-
`${scopeName} queryEveryDocument reads every record in id order, so its query cannot name ${key}; sort the records it returns.`
|
|
128
|
-
);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
132
|
-
queryAllJsonRestCollectionDocument(
|
|
133
|
-
requireApiResource(),
|
|
134
|
-
{
|
|
135
|
-
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
136
|
-
transaction: resolveTransaction(options)
|
|
137
|
-
},
|
|
138
|
-
options.context
|
|
139
|
-
)
|
|
140
|
-
);
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// Locks the record's row until trx ends, so another forUpdate read or a write
|
|
144
|
-
// of it waits. SQLite runs one transaction at a time on knex's single
|
|
145
|
-
// connection, so it has no row lock to take.
|
|
146
|
-
async function lockRecord(recordId, trx) {
|
|
147
|
-
if (/sqlite/.test(String(trx.client.config.client))) {
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
const storage = api.knex.helpers.getStorageAdapter(scopeName);
|
|
151
|
-
await storage.buildBaseQuery({ transaction: trx })
|
|
152
|
-
.where(storage.getIdColumn(), storage.translateFilterValue("id", recordId))
|
|
153
|
-
.forUpdate()
|
|
154
|
-
.first(storage.getIdColumn());
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* One record as a JSON:API document, or null when it is missing or hidden.
|
|
159
|
-
* `options.forUpdate: true` first locks its row in `options.trx` (required)
|
|
160
|
-
* until that transaction ends, so a concurrent forUpdate read or write of it
|
|
161
|
-
* waits: read, check and write inside one transaction without a lost update.
|
|
162
|
-
* The lock comes before the read, so on PostgreSQL (READ COMMITTED) the read
|
|
163
|
-
* sees the latest version; on MySQL's REPEATABLE READ it does when the lock
|
|
164
|
-
* is the transaction's first read.
|
|
165
|
-
* @param {unknown} recordId
|
|
166
|
-
* @param {Record<string, unknown>} [query]
|
|
167
|
-
* @param {{ trx?: any, context?: object | null, forUpdate?: boolean }} [options]
|
|
168
|
-
*/
|
|
169
|
-
async function getDocumentById(recordId, query = {}, options = {}) {
|
|
170
|
-
if (options.forUpdate != null && typeof options.forUpdate !== "boolean") {
|
|
171
|
-
throw new TypeError(`${scopeName} getDocumentById forUpdate must be true or false. Received: ${options.forUpdate}`);
|
|
172
|
-
}
|
|
173
|
-
if (options.forUpdate) {
|
|
174
|
-
const trx = resolveTransaction(options);
|
|
175
|
-
if (!trx) {
|
|
176
|
-
throw new TypeError(
|
|
177
|
-
`${scopeName} getDocumentById forUpdate locks the record until its transaction ends, so it needs options.trx ` +
|
|
178
|
-
"(run it inside withTransaction)."
|
|
179
|
-
);
|
|
180
|
-
}
|
|
181
|
-
await lockRecord(recordId, trx);
|
|
182
|
-
}
|
|
183
|
-
return returnBadRequestWhenJsonRestFieldsetInvalid(() =>
|
|
184
|
-
returnNullWhenJsonRestResourceMissing(() =>
|
|
185
|
-
requireApiResource().get(
|
|
186
|
-
{
|
|
187
|
-
id: recordId,
|
|
188
|
-
queryParams: buildJsonRestQueryParams(scopeName, query),
|
|
189
|
-
transaction: resolveTransaction(options),
|
|
190
|
-
format: "jsonapi"
|
|
191
|
-
},
|
|
192
|
-
createJsonRestContext(options.context)
|
|
193
|
-
)
|
|
194
|
-
)
|
|
195
|
-
);
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
function post(payload, returning, options) {
|
|
199
|
-
return requireApiResource().post(
|
|
200
|
-
{
|
|
201
|
-
data: inputData(payload),
|
|
202
|
-
returning,
|
|
203
|
-
transaction: resolveTransaction(options),
|
|
204
|
-
format: "jsonapi"
|
|
205
|
-
},
|
|
206
|
-
createJsonRestContext(options.context)
|
|
207
|
-
);
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
/**
|
|
211
|
-
* Creates one record. `options.returning` picks the result: "full" (the
|
|
212
|
-
* default) reads the new record back through its row policy and lookups;
|
|
213
|
-
* "minimal" answers `{ data: { type, id } }` and "none" undefined, without
|
|
214
|
-
* that read.
|
|
215
|
-
* @param {Record<string, unknown>} [payload]
|
|
216
|
-
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
217
|
-
*/
|
|
218
|
-
async function createDocument(payload = {}, options = {}) {
|
|
219
|
-
const returning = writeReturning(options);
|
|
220
|
-
return write(options, () => post(payload, returning, options));
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Creates every payload, in order, in one transaction: the caller's `trx`,
|
|
225
|
-
* or one it owns and retries whole on a deadlock, so either all are created
|
|
226
|
-
* or none. Results follow the payloads' order; `options.returning` is
|
|
227
|
-
* "minimal" by default, so no record is read back.
|
|
228
|
-
* @param {Record<string, unknown>[]} payloads
|
|
229
|
-
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
230
|
-
*/
|
|
231
|
-
async function createDocuments(payloads, options = {}) {
|
|
232
|
-
if (!Array.isArray(payloads)) {
|
|
233
|
-
throw new TypeError("createDocuments requires an array of payloads.");
|
|
234
|
-
}
|
|
235
|
-
const returning = writeReturning(options, "minimal");
|
|
236
|
-
async function createAll(trx) {
|
|
237
|
-
const results = [];
|
|
238
|
-
for (const payload of payloads) {
|
|
239
|
-
results.push(await post(payload, returning, { ...options, trx }));
|
|
240
|
-
}
|
|
241
|
-
return results;
|
|
242
|
-
}
|
|
243
|
-
const trx = resolveTransaction(options);
|
|
244
|
-
return trx ? createAll(trx) : withTransaction(createAll);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Patches one record; null when it does not exist or is out of the
|
|
249
|
-
* caller's scope. `options.returning` picks the result as createDocument's.
|
|
250
|
-
* @param {string | number} recordId
|
|
251
|
-
* @param {Record<string, unknown>} patch
|
|
252
|
-
* @param {{ trx?: any, context?: object | null, returning?: WriteReturning }} [options]
|
|
253
|
-
*/
|
|
254
|
-
async function patchDocumentById(recordId, patch, options = {}) {
|
|
255
|
-
const returning = writeReturning(options);
|
|
256
|
-
if (Object.keys(patch).length < 1) {
|
|
257
|
-
const document = await getDocumentById(recordId, {}, options);
|
|
258
|
-
if (!document || returning === "full") {
|
|
259
|
-
return document;
|
|
260
|
-
}
|
|
261
|
-
return returning === "minimal" ? { data: { type: scopeName, id: document.data.id } } : undefined;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
return returnNullWhenJsonRestResourceMissing(() => write(options, () =>
|
|
265
|
-
requireApiResource().patch(
|
|
266
|
-
{
|
|
267
|
-
id: recordId,
|
|
268
|
-
data: inputData(patch),
|
|
269
|
-
returning,
|
|
270
|
-
transaction: resolveTransaction(options),
|
|
271
|
-
format: "jsonapi"
|
|
272
|
-
},
|
|
273
|
-
createJsonRestContext(options.context)
|
|
274
|
-
)
|
|
275
|
-
));
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
/**
|
|
279
|
-
* Patches a record only while its lockVersionField still holds
|
|
280
|
-
* expectedLockVersion, and adds one to it in the same transaction: the
|
|
281
|
-
* caller's `trx`, or one it owns. Returns the patched document, or null when
|
|
282
|
-
* the record does not exist or is out of the caller's scope; a record whose
|
|
283
|
-
* lock version has moved on rejects with a 409 `crud.document.lockVersionConflict`.
|
|
284
|
-
* @param {string | number} recordId
|
|
285
|
-
* @param {number} expectedLockVersion
|
|
286
|
-
* @param {Record<string, unknown>} patch
|
|
287
|
-
* @param {{ trx?: any, context?: object }} [options]
|
|
288
|
-
*/
|
|
289
|
-
async function patchDocumentIfLockVersion(recordId, expectedLockVersion, patch, options = {}) {
|
|
290
|
-
const lockVersionField = resource.lockVersionField;
|
|
291
|
-
if (!lockVersionField) {
|
|
292
|
-
throw new TypeError(`patchDocumentIfLockVersion needs resource "${scopeName}" to name its lockVersionField.`);
|
|
293
|
-
}
|
|
294
|
-
if (!Number.isSafeInteger(expectedLockVersion) || expectedLockVersion < 0) {
|
|
295
|
-
throw new TypeError(`patchDocumentIfLockVersion expectedLockVersion must be a non-negative integer. Received: ${expectedLockVersion}`);
|
|
296
|
-
}
|
|
297
|
-
if (Object.hasOwn(patch, lockVersionField)) {
|
|
298
|
-
throw new TypeError(`patchDocumentIfLockVersion advances ${lockVersionField} itself, so the patch must leave it out.`);
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
async function patchAtLockVersion(trx) {
|
|
302
|
-
const scoped = { ...options, trx };
|
|
303
|
-
if (!await getDocumentById(recordId, {}, scoped)) {
|
|
304
|
-
return null;
|
|
305
|
-
}
|
|
306
|
-
const storage = api.knex.helpers.getStorageAdapter(scopeName);
|
|
307
|
-
const lockColumn = storage.translateColumn(lockVersionField);
|
|
308
|
-
const claimed = await storage.buildBaseQuery({ transaction: trx })
|
|
309
|
-
.where(storage.getIdColumn(), storage.translateFilterValue("id", recordId))
|
|
310
|
-
.where(lockColumn, expectedLockVersion)
|
|
311
|
-
.update({ [lockColumn]: expectedLockVersion + 1 });
|
|
312
|
-
if (claimed < 1) {
|
|
313
|
-
throw new AppError(409, "This record changed. Reload and try again.", {
|
|
314
|
-
code: "crud.document.lockVersionConflict"
|
|
315
|
-
});
|
|
316
|
-
}
|
|
317
|
-
return patchDocumentById(recordId, patch, scoped);
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
const trx = resolveTransaction(options);
|
|
321
|
-
return trx
|
|
322
|
-
? patchAtLockVersion(trx)
|
|
323
|
-
: returnNullWhenJsonRestResourceMissing(() => withTransaction(patchAtLockVersion));
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
async function deleteDocumentById(recordId, options = {}) {
|
|
327
|
-
return returnNullWhenJsonRestResourceMissing(async () => {
|
|
328
|
-
await write(options, () => requireApiResource().delete(
|
|
329
|
-
{
|
|
330
|
-
id: recordId,
|
|
331
|
-
returning: "none",
|
|
332
|
-
transaction: resolveTransaction(options),
|
|
333
|
-
format: "jsonapi"
|
|
334
|
-
},
|
|
335
|
-
createJsonRestContext(options.context)
|
|
336
|
-
));
|
|
337
|
-
return null;
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
return Object.freeze({
|
|
342
|
-
withTransaction,
|
|
343
|
-
queryMaxLimit,
|
|
344
|
-
queryDocuments,
|
|
345
|
-
queryEveryDocument,
|
|
346
|
-
getDocumentById,
|
|
347
|
-
createDocument,
|
|
348
|
-
createDocuments,
|
|
349
|
-
patchDocumentById,
|
|
350
|
-
patchDocumentIfLockVersion,
|
|
351
|
-
deleteDocumentById
|
|
352
|
-
});
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
export { createCrudJsonApiRepository };
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { normalizeCrudLookupNamespace } from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
2
|
-
import { normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
3
|
-
import { toSnakeCase } from "@jskit-ai/kernel/shared/support/stringCase";
|
|
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
|
-
|
|
33
|
-
function requireCrudLookupNamespace(value = "", { context = "crudLookup" } = {}) {
|
|
34
|
-
const normalizedNamespace = normalizeCrudLookupNamespace(value);
|
|
35
|
-
if (!normalizedNamespace) {
|
|
36
|
-
throw new Error(`${context} requires relation.namespace.`);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
return normalizedNamespace;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function resolveCrudLookupToken(namespace = "", { context = "crudLookup" } = {}) {
|
|
43
|
-
const normalizedNamespace = requireCrudLookupNamespace(namespace, {
|
|
44
|
-
context
|
|
45
|
-
});
|
|
46
|
-
const tokenPart = normalizedNamespace
|
|
47
|
-
.split("/")
|
|
48
|
-
.map((segment) => toSnakeCase(segment))
|
|
49
|
-
.filter(Boolean)
|
|
50
|
-
.join(".");
|
|
51
|
-
return `lookup.${tokenPart}`;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export {
|
|
55
|
-
normalizeLookupOwnershipFilter,
|
|
56
|
-
requireCrudLookupNamespace,
|
|
57
|
-
resolveCrudLookupToken
|
|
58
|
-
};
|
package/src/server/lookups.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
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
|
-
*/
|
|
10
|
-
function createCrudLookup(repository, { context = "crudLookup", ownershipFilter = "" } = {}) {
|
|
11
|
-
// readable-check: allow method-probe - input validation: the application passes its own repository
|
|
12
|
-
if (!repository || typeof repository.listByIds !== "function") {
|
|
13
|
-
throw new Error(`${context} requires repository.listByIds(ids, options).`);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const normalizedOwnershipFilter = normalizeLookupOwnershipFilter(
|
|
17
|
-
ownershipFilter || repository.ownershipFilter,
|
|
18
|
-
{
|
|
19
|
-
context: `${context} ownershipFilter`
|
|
20
|
-
}
|
|
21
|
-
);
|
|
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
|
-
|
|
31
|
-
return Object.freeze({
|
|
32
|
-
ownershipFilter: normalizedOwnershipFilter || null,
|
|
33
|
-
listByIds
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export {
|
|
38
|
-
resolveCrudLookupToken,
|
|
39
|
-
createCrudLookup
|
|
40
|
-
};
|