@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.
Files changed (60) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/locales/en.json +1 -11
  3. package/package.json +19 -19
  4. package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  5. package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  6. package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  7. package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  8. package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  9. package/src/server/createHooksToCollectChildren.js +56 -34
  10. package/src/server/crudContracts.js +54 -0
  11. package/src/server/defineCrudFeature.js +538 -0
  12. package/src/server/jsonApiModule/actions.js +117 -59
  13. package/src/server/jsonApiModule/routes.js +35 -11
  14. package/src/server/jsonApiModule/service.js +227 -32
  15. package/src/server/jsonApiResourceContract.js +41 -1
  16. package/src/server/listQueryValidators.js +1 -1
  17. package/src/server/removedApi.js +87 -0
  18. package/src/server/types.js +26 -50
  19. package/test/assistantActionConformance.test.js +20 -21
  20. package/test/assistantPagination.integration.test.js +32 -42
  21. package/test/createHooksToCollectChildren.test.js +61 -16
  22. package/test/crudFeaturePackagePattern.test.js +51 -0
  23. package/test/crudOnHandles.test.js +451 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +451 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +63 -0
  27. package/test/listQueryValidators.test.js +1 -1
  28. package/test/routeContracts.test.js +1 -1
  29. package/test/support/crudJsonApiActionOptions.js +3 -3
  30. package/test/unservedCrudAutomation.test.js +27 -22
  31. package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  32. package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  33. package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  34. package/src/server/createCrudServiceFromResource.js +0 -63
  35. package/src/server/defineCrudJsonApiFeature.js +0 -346
  36. package/src/server/fieldAccess.js +0 -298
  37. package/src/server/jsonApiModule/repository.js +0 -355
  38. package/src/server/lookupPathSupport.js +0 -58
  39. package/src/server/lookups.js +0 -40
  40. package/src/server/repositorySupport.js +0 -528
  41. package/src/server/resourceRuntime/compiledRuntime.js +0 -284
  42. package/src/server/resourceRuntime/index.js +0 -659
  43. package/src/server/resourceRuntime/listControls.js +0 -333
  44. package/src/server/resourceRuntime/lookupHydration.js +0 -626
  45. package/src/server/resourceRuntime/operationStages.js +0 -140
  46. package/src/server/resourceRuntime/recordValidation.js +0 -65
  47. package/src/server/serviceMethods.js +0 -149
  48. package/test/createCrudServiceFromResource.test.js +0 -323
  49. package/test/fieldAccess.test.js +0 -86
  50. package/test/jsonApiRepository.test.js +0 -333
  51. package/test/jsonApiRepositoryDataCosts.test.js +0 -183
  52. package/test/jsonApiRepositoryPageLimits.test.js +0 -158
  53. package/test/jsonApiRepositoryRowLocks.test.js +0 -137
  54. package/test/jsonApiResourcePackagePattern.test.js +0 -20
  55. package/test/lookups.test.js +0 -111
  56. package/test/repositorySupport.test.js +0 -767
  57. package/test/resourceRuntime.test.js +0 -1014
  58. package/test/serviceMethods.test.js +0 -139
  59. /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  60. /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -1,659 +0,0 @@
1
- import {
2
- createWithTransaction,
3
- resolveInsertedRecordId,
4
- resolveRepoClient,
5
- toInsertDateTime
6
- } from "@jskit-ai/database-runtime/shared";
7
- import { applyVisibility, applyVisibilityOwners } from "@jskit-ai/database-runtime/shared/visibility";
8
- import { normalizeRecordId, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
9
- import {
10
- normalizeCrudListLimit,
11
- applyCrudListQueryFilters,
12
- buildWritePayload,
13
- mapRecordRow,
14
- resolveColumnName
15
- } from "../repositorySupport.js";
16
- import { hydrateCrudLookupRecords } from "./lookupHydration.js";
17
- import { CRUD_FIELD_STORAGE_COLUMN } from "@jskit-ai/resource-crud-core/shared/crudFieldContract";
18
- import {
19
- applyCrudRepositoryVirtualProjections,
20
- applyConfiguredQueryStage,
21
- applyConfiguredObjectStage,
22
- buildCrudRepositoryActionContextBase
23
- } from "./operationStages.js";
24
- import {
25
- encodeOrderedListCursor,
26
- applyOrderedListCursorFilter,
27
- enforceCrudRepositoryListControls
28
- } from "./listControls.js";
29
- import {
30
- normalizeRepositoryInputPayload,
31
- normalizeRepositoryOutputRecord
32
- } from "./recordValidation.js";
33
- import { buildCompiledCrudRepositoryRuntime } from "./compiledRuntime.js";
34
-
35
- /** @typedef {import("@jskit-ai/database-runtime/server/types").RuntimeKnex} RuntimeKnex */
36
-
37
- function requireCrudRecordId(value, { context }) {
38
- const recordId = normalizeRecordId(value, { fallback: null });
39
- if (!recordId) {
40
- throw new TypeError(`${context} requires recordId.`);
41
- }
42
- return recordId;
43
- }
44
-
45
- /**
46
- * What one repository call reads and writes through: the call's transaction
47
- * (else the repository's Knex), with the runtime's table and id column, and the
48
- * visibility filter of the call's visibility context.
49
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
50
- * @param {RuntimeKnex} knex
51
- * @param {object} callOptions
52
- */
53
- function resolveCrudRepositoryCall(runtime, knex, callOptions) {
54
- return Object.freeze({
55
- client: resolveRepoClient(knex, callOptions),
56
- tableName: runtime.tableName,
57
- idColumn: runtime.idColumn,
58
- visible: (queryBuilder) => applyVisibility(queryBuilder, callOptions.visibilityContext)
59
- });
60
- }
61
-
62
- function applyCrudRepositoryReadLock(dbQuery, callOptions) {
63
- if (callOptions.forUpdate === true) {
64
- return dbQuery.forUpdate();
65
- }
66
-
67
- return dbQuery;
68
- }
69
-
70
- /**
71
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
72
- * @param {RuntimeKnex} knex
73
- * @param {object} query
74
- * @param {object} callOptions
75
- */
76
- async function listRecords(runtime, knex, query, callOptions) {
77
- const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
78
- const normalizedLimit = normalizeCrudListLimit(query.limit, {
79
- fallback: runtime.list.defaultLimit,
80
- max: runtime.list.maxLimit
81
- });
82
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
83
- const usesOrderedListCursor = runtime.list.orderBy.length > 0;
84
- let dbQuery = client(tableName)
85
- .select(...runtime.selectColumns);
86
- dbQuery = applyCrudRepositoryVirtualProjections(dbQuery, runtime, {
87
- knex: client,
88
- tableName
89
- });
90
-
91
- dbQuery = applyCrudListQueryFilters(dbQuery, {
92
- idColumn,
93
- cursor: query.cursor,
94
- applyCursor: usesOrderedListCursor !== true,
95
- q: query.q,
96
- searchColumns: runtime.list.searchColumns,
97
- parentFilters: query,
98
- parentFilterColumns: runtime.mapping.parentFilterColumns
99
- });
100
- if (usesOrderedListCursor) {
101
- dbQuery = applyOrderedListCursorFilter(dbQuery, {
102
- orderBy: runtime.list.orderBy,
103
- cursor: query.cursor
104
- });
105
- }
106
-
107
- const readListStageResult = await applyConfiguredQueryStage(
108
- dbQuery,
109
- runtime.operations.read.applyQuery,
110
- {
111
- action: "list",
112
- query,
113
- ...actionContextBase
114
- },
115
- {
116
- context: runtime.context,
117
- stageKey: "operations.read.applyQuery"
118
- }
119
- );
120
- dbQuery = readListStageResult.queryBuilder;
121
- const listStageResult = await applyConfiguredQueryStage(
122
- dbQuery,
123
- runtime.operations.list.applyQuery,
124
- {
125
- action: "list",
126
- query,
127
- ...actionContextBase
128
- },
129
- {
130
- context: runtime.context,
131
- stageKey: "operations.list.applyQuery"
132
- }
133
- );
134
- dbQuery = listStageResult.queryBuilder;
135
-
136
- dbQuery = dbQuery.where(visible);
137
- dbQuery = applyCrudRepositoryReadLock(dbQuery, callOptions);
138
- dbQuery = enforceCrudRepositoryListControls(dbQuery, {
139
- idColumn,
140
- limit: normalizedLimit + 1,
141
- orderBy: runtime.list.orderBy
142
- });
143
-
144
- const rows = await dbQuery;
145
- const hasMore = rows.length > normalizedLimit;
146
- const pageRows = hasMore ? rows.slice(0, normalizedLimit) : rows;
147
- const items = [];
148
- for (const row of pageRows) {
149
- const mappedRecord = mapRecordRow(
150
- row,
151
- runtime.mapping.outputKeys,
152
- runtime.mapping.columnOverrides,
153
- {
154
- recordIdKeys: runtime.mapping.outputRecordIdKeys,
155
- serializerByKey: runtime.mapping.outputSerializerByKey
156
- }
157
- );
158
- if (!mappedRecord) {
159
- continue;
160
- }
161
-
162
- items.push(await normalizeRepositoryOutputRecord(runtime, mappedRecord, {
163
- operation: "list"
164
- }));
165
- }
166
-
167
- const hydratedItems = await hydrateCrudLookupRecords(items, runtime.lookup, {
168
- include: callOptions.include,
169
- mode: "list",
170
- repositoryOptions: runtime.repositoryOptions,
171
- callOptions
172
- });
173
-
174
- const lastPageRow = pageRows[pageRows.length - 1] || null;
175
- const nextCursor = hasMore && lastPageRow
176
- ? (
177
- usesOrderedListCursor
178
- ? encodeOrderedListCursor(lastPageRow, runtime.list.orderBy)
179
- : String(lastPageRow[idColumn])
180
- )
181
- : null;
182
-
183
- return {
184
- items: hydratedItems,
185
- nextCursor
186
- };
187
- }
188
-
189
- /**
190
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
191
- * @param {RuntimeKnex} knex
192
- * @param {unknown} recordId
193
- * @param {object} callOptions
194
- */
195
- async function findRecordById(runtime, knex, recordId, callOptions) {
196
- const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
197
- const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.findById" });
198
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
199
- let dbQuery = client(tableName)
200
- .select(...runtime.selectColumns);
201
- dbQuery = applyCrudRepositoryVirtualProjections(dbQuery, runtime, {
202
- knex: client,
203
- tableName
204
- });
205
-
206
- const readFindStageResult = await applyConfiguredQueryStage(
207
- dbQuery,
208
- runtime.operations.read.applyQuery,
209
- {
210
- action: "findById",
211
- recordId,
212
- ...actionContextBase
213
- },
214
- {
215
- context: runtime.context,
216
- stageKey: "operations.read.applyQuery"
217
- }
218
- );
219
- dbQuery = readFindStageResult.queryBuilder;
220
- const findStageResult = await applyConfiguredQueryStage(
221
- dbQuery,
222
- runtime.operations.findById.applyQuery,
223
- {
224
- action: "findById",
225
- recordId,
226
- ...actionContextBase
227
- },
228
- {
229
- context: runtime.context,
230
- stageKey: "operations.findById.applyQuery"
231
- }
232
- );
233
- dbQuery = findStageResult.queryBuilder;
234
-
235
- dbQuery = dbQuery
236
- .where(visible)
237
- .where({
238
- [idColumn]: normalizedRecordId
239
- });
240
- dbQuery = applyCrudRepositoryReadLock(dbQuery, callOptions);
241
-
242
- const row = await dbQuery.first();
243
-
244
- const mappedRecord = mapRecordRow(
245
- row,
246
- runtime.mapping.outputKeys,
247
- runtime.mapping.columnOverrides,
248
- {
249
- recordIdKeys: runtime.mapping.outputRecordIdKeys,
250
- serializerByKey: runtime.mapping.outputSerializerByKey
251
- }
252
- );
253
- if (!mappedRecord) {
254
- return null;
255
- }
256
-
257
- const normalizedRecord = await normalizeRepositoryOutputRecord(runtime, mappedRecord, {
258
- operation: "findById"
259
- });
260
- const hydrated = await hydrateCrudLookupRecords([normalizedRecord], runtime.lookup, {
261
- include: callOptions.include,
262
- mode: "view",
263
- repositoryOptions: runtime.repositoryOptions,
264
- callOptions
265
- });
266
-
267
- return hydrated[0] || null;
268
- }
269
-
270
- /**
271
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
272
- * @param {RuntimeKnex} knex
273
- * @param {unknown[]} ids
274
- * @param {object} callOptions
275
- */
276
- async function listRecordsByIds(runtime, knex, ids, callOptions) {
277
- const { client, tableName, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
278
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
279
- const lookupValueKey = normalizeText(callOptions.valueKey) || "id";
280
- if (!runtime.mapping.outputKeys.includes(lookupValueKey)) {
281
- throw new TypeError(
282
- `${runtime.context} listByIds requires valueKey "${lookupValueKey}" to exist in output schema.`
283
- );
284
- }
285
- if (runtime.mapping.fieldStorageByKey[lookupValueKey] !== CRUD_FIELD_STORAGE_COLUMN) {
286
- throw new TypeError(
287
- `${runtime.context} listByIds requires valueKey "${lookupValueKey}" to be column-backed.`
288
- );
289
- }
290
- const lookupColumn = resolveColumnName(lookupValueKey, runtime.mapping.columnOverrides);
291
- if (!lookupColumn) {
292
- throw new TypeError(`${runtime.context} listByIds requires a valid valueKey.`);
293
- }
294
-
295
- const normalizedIds = Array.isArray(ids)
296
- ? [...new Set(ids.map((value) => normalizeText(value)).filter(Boolean))]
297
- : [];
298
- if (normalizedIds.length < 1) {
299
- return [];
300
- }
301
-
302
- let dbQuery = client(tableName)
303
- .select(...runtime.selectColumns);
304
- dbQuery = applyCrudRepositoryVirtualProjections(dbQuery, runtime, {
305
- knex: client,
306
- tableName
307
- });
308
-
309
- const readListByIdsStageResult = await applyConfiguredQueryStage(
310
- dbQuery,
311
- runtime.operations.read.applyQuery,
312
- {
313
- action: "listByIds",
314
- ids: normalizedIds,
315
- lookupValueKey,
316
- lookupColumn,
317
- ...actionContextBase
318
- },
319
- {
320
- context: runtime.context,
321
- stageKey: "operations.read.applyQuery"
322
- }
323
- );
324
- dbQuery = readListByIdsStageResult.queryBuilder;
325
- const listByIdsStageResult = await applyConfiguredQueryStage(
326
- dbQuery,
327
- runtime.operations.listByIds.applyQuery,
328
- {
329
- action: "listByIds",
330
- ids: normalizedIds,
331
- lookupValueKey,
332
- lookupColumn,
333
- ...actionContextBase
334
- },
335
- {
336
- context: runtime.context,
337
- stageKey: "operations.listByIds.applyQuery"
338
- }
339
- );
340
- dbQuery = listByIdsStageResult.queryBuilder;
341
-
342
- dbQuery = dbQuery
343
- .where(visible)
344
- .whereIn(lookupColumn, normalizedIds);
345
- dbQuery = applyCrudRepositoryReadLock(dbQuery, callOptions);
346
-
347
- const rows = await dbQuery;
348
-
349
- const records = [];
350
- for (const row of rows) {
351
- const mappedRecord = mapRecordRow(
352
- row,
353
- runtime.mapping.outputKeys,
354
- runtime.mapping.columnOverrides,
355
- {
356
- recordIdKeys: runtime.mapping.outputRecordIdKeys,
357
- serializerByKey: runtime.mapping.outputSerializerByKey
358
- }
359
- );
360
- if (!mappedRecord) {
361
- continue;
362
- }
363
-
364
- records.push(await normalizeRepositoryOutputRecord(runtime, mappedRecord, {
365
- operation: "listByIds"
366
- }));
367
- }
368
-
369
- const lookupInclude = callOptions.include === undefined ? "none" : callOptions.include;
370
- return hydrateCrudLookupRecords(records, runtime.lookup, {
371
- include: lookupInclude,
372
- mode: "list",
373
- repositoryOptions: runtime.repositoryOptions,
374
- callOptions
375
- });
376
- }
377
-
378
- /**
379
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
380
- * @param {RuntimeKnex} knex
381
- * @param {object} payload
382
- * @param {object} callOptions
383
- */
384
- async function createRecord(runtime, knex, payload, callOptions) {
385
- const { client, tableName } = resolveCrudRepositoryCall(runtime, knex, callOptions);
386
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
387
- let sourcePayload = await normalizeRepositoryInputPayload(runtime, payload, "create");
388
- sourcePayload = await applyConfiguredObjectStage(
389
- sourcePayload,
390
- runtime.operations.create.preparePayload,
391
- {
392
- action: "create",
393
- payload: sourcePayload,
394
- ...actionContextBase
395
- },
396
- {
397
- context: runtime.context,
398
- stageKey: "operations.create.preparePayload"
399
- }
400
- );
401
-
402
- let insertPayload = buildWritePayload(
403
- sourcePayload,
404
- runtime.mapping.writeKeys,
405
- runtime.mapping.columnOverrides,
406
- {
407
- serializerByKey: runtime.mapping.writeSerializerByKey
408
- }
409
- );
410
- const timestamp = toInsertDateTime();
411
- if (runtime.defaults.createdAtColumn && !Object.hasOwn(insertPayload, runtime.defaults.createdAtColumn)) {
412
- insertPayload[runtime.defaults.createdAtColumn] = timestamp;
413
- }
414
- if (runtime.defaults.updatedAtColumn && !Object.hasOwn(insertPayload, runtime.defaults.updatedAtColumn)) {
415
- insertPayload[runtime.defaults.updatedAtColumn] = timestamp;
416
- }
417
- insertPayload = await applyConfiguredObjectStage(
418
- insertPayload,
419
- runtime.operations.create.prepareInsertPayload,
420
- {
421
- action: "create",
422
- payload: sourcePayload,
423
- insertPayload: {
424
- ...insertPayload
425
- },
426
- ...actionContextBase
427
- },
428
- {
429
- context: runtime.context,
430
- stageKey: "operations.create.prepareInsertPayload"
431
- }
432
- );
433
-
434
- const withOwners = applyVisibilityOwners(insertPayload, callOptions.visibilityContext);
435
- let createQuery = client(tableName);
436
- const createStageResult = await applyConfiguredQueryStage(
437
- createQuery,
438
- runtime.operations.create.applyQuery,
439
- {
440
- action: "create",
441
- payload: {
442
- ...withOwners
443
- },
444
- ...actionContextBase
445
- },
446
- {
447
- context: runtime.context,
448
- stageKey: "operations.create.applyQuery"
449
- }
450
- );
451
- createQuery = createStageResult.queryBuilder;
452
-
453
- const insertResult = await createQuery.insert(withOwners);
454
- const recordId = resolveInsertedRecordId(insertResult, { fallback: null });
455
- if (!recordId) {
456
- throw new Error("crudRepository.create could not resolve inserted id.");
457
- }
458
-
459
- return findRecordById(runtime, knex, recordId, {
460
- ...callOptions,
461
- trx: client,
462
- sourceOperation: "create"
463
- });
464
- }
465
-
466
- /**
467
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
468
- * @param {RuntimeKnex} knex
469
- * @param {unknown} recordId
470
- * @param {object} patch
471
- * @param {object} callOptions
472
- */
473
- async function updateRecordById(runtime, knex, recordId, patch, callOptions) {
474
- const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
475
- const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.updateById" });
476
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
477
- let sourcePatch = await normalizeRepositoryInputPayload(runtime, patch, "patch");
478
- sourcePatch = await applyConfiguredObjectStage(
479
- sourcePatch,
480
- runtime.operations.updateById.preparePatch,
481
- {
482
- action: "updateById",
483
- recordId,
484
- patch: sourcePatch,
485
- ...actionContextBase
486
- },
487
- {
488
- context: runtime.context,
489
- stageKey: "operations.updateById.preparePatch"
490
- }
491
- );
492
- const dbPatch = buildWritePayload(
493
- sourcePatch,
494
- runtime.mapping.writeKeys,
495
- runtime.mapping.columnOverrides,
496
- {
497
- serializerByKey: runtime.mapping.writeSerializerByKey
498
- }
499
- );
500
-
501
- if (runtime.defaults.updatedAtColumn) {
502
- dbPatch[runtime.defaults.updatedAtColumn] = toInsertDateTime();
503
- }
504
-
505
- if (Object.keys(dbPatch).length < 1) {
506
- return findRecordById(runtime, knex, recordId, {
507
- ...callOptions,
508
- trx: client,
509
- sourceOperation: "update"
510
- });
511
- }
512
-
513
- let updateQuery = client(tableName);
514
- const updateStageResult = await applyConfiguredQueryStage(
515
- updateQuery,
516
- runtime.operations.updateById.applyQuery,
517
- {
518
- action: "updateById",
519
- recordId,
520
- patch: {
521
- ...dbPatch
522
- },
523
- ...actionContextBase
524
- },
525
- {
526
- context: runtime.context,
527
- stageKey: "operations.updateById.applyQuery"
528
- }
529
- );
530
- updateQuery = updateStageResult.queryBuilder;
531
-
532
- updateQuery = updateQuery
533
- .where(visible)
534
- .where({
535
- [idColumn]: normalizedRecordId
536
- });
537
-
538
- await updateQuery.update(dbPatch);
539
-
540
- return findRecordById(runtime, knex, recordId, {
541
- ...callOptions,
542
- trx: client,
543
- sourceOperation: "update"
544
- });
545
- }
546
-
547
- /**
548
- * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
549
- * @param {RuntimeKnex} knex
550
- * @param {unknown} recordId
551
- * @param {object} callOptions
552
- */
553
- async function deleteRecordById(runtime, knex, recordId, callOptions) {
554
- const { client, tableName, idColumn, visible } = resolveCrudRepositoryCall(runtime, knex, callOptions);
555
- const normalizedRecordId = requireCrudRecordId(recordId, { context: "crudRepository.deleteById" });
556
- const actionContextBase = buildCrudRepositoryActionContextBase(runtime, callOptions);
557
- const existing = await findRecordById(runtime, knex, recordId, {
558
- ...callOptions,
559
- include: "none",
560
- trx: client
561
- });
562
- if (!existing) {
563
- return null;
564
- }
565
-
566
- let deleteQuery = client(tableName);
567
- const deleteStageResult = await applyConfiguredQueryStage(
568
- deleteQuery,
569
- runtime.operations.deleteById.applyQuery,
570
- {
571
- action: "deleteById",
572
- recordId,
573
- existing,
574
- ...actionContextBase
575
- },
576
- {
577
- context: runtime.context,
578
- stageKey: "operations.deleteById.applyQuery"
579
- }
580
- );
581
- deleteQuery = deleteStageResult.queryBuilder;
582
-
583
- deleteQuery = deleteQuery
584
- .where(visible)
585
- .where({
586
- [idColumn]: normalizedRecordId
587
- });
588
-
589
- await deleteQuery.delete();
590
-
591
- return {
592
- id: existing.id,
593
- deleted: true
594
- };
595
- }
596
-
597
- /**
598
- * @param {import("../types.js").CrudResourceDefinition} resource
599
- * @param {RuntimeKnex} knex
600
- * @param {object} [repositoryOptions]
601
- */
602
- function createCrudResourceRuntime(resource, knex, repositoryOptions = {}) {
603
- // readable-check: allow method-probe - input validation: the application passes its own Knex instance
604
- if (typeof knex !== "function" || typeof knex.transaction !== "function") {
605
- throw new TypeError("createCrudResourceRuntime requires the application's Knex instance.");
606
- }
607
-
608
- const runtime = buildCompiledCrudRepositoryRuntime(resource, repositoryOptions);
609
- const withTransaction = createWithTransaction(knex);
610
-
611
- async function list(query = {}, callOptions = {}) {
612
- return listRecords(runtime, knex, query, callOptions);
613
- }
614
-
615
- async function findById(recordId, callOptions = {}) {
616
- return findRecordById(runtime, knex, recordId, callOptions);
617
- }
618
-
619
- async function listByIds(ids = [], callOptions = {}) {
620
- return listRecordsByIds(runtime, knex, ids, callOptions);
621
- }
622
-
623
- async function listByForeignIds(ids = [], foreignKey = "", callOptions = {}) {
624
- const normalizedForeignKey = normalizeText(foreignKey);
625
- if (!normalizedForeignKey) {
626
- throw new TypeError(`${runtime.context} listByForeignIds requires foreignKey.`);
627
- }
628
-
629
- return listRecordsByIds(runtime, knex, ids, {
630
- ...callOptions,
631
- valueKey: normalizedForeignKey
632
- });
633
- }
634
-
635
- async function create(payload = {}, callOptions = {}) {
636
- return createRecord(runtime, knex, payload, callOptions);
637
- }
638
-
639
- async function updateById(recordId, patch = {}, callOptions = {}) {
640
- return updateRecordById(runtime, knex, recordId, patch, callOptions);
641
- }
642
-
643
- async function deleteById(recordId, callOptions = {}) {
644
- return deleteRecordById(runtime, knex, recordId, callOptions);
645
- }
646
-
647
- return Object.freeze({
648
- withTransaction,
649
- list,
650
- findById,
651
- listByIds,
652
- listByForeignIds,
653
- create,
654
- updateById,
655
- deleteById
656
- });
657
- }
658
-
659
- export { createCrudResourceRuntime };