@jskit-ai/crud-core 0.2.2 → 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.
Files changed (48) hide show
  1. package/locales/en.json +2 -1
  2. package/package.json +7 -7
  3. package/patterns/json-api-resource-package/PATTERN.md +102 -23
  4. package/patterns/json-api-resource-package/example/packages/books/package.json +3 -2
  5. package/patterns/json-api-resource-package/example/packages/books/src/server/types.js +5 -0
  6. package/src/server/createCrudServiceFromResource.js +14 -6
  7. package/src/server/createHooksToCollectChildren.js +123 -97
  8. package/src/server/defineCrudJsonApiFeature.js +40 -8
  9. package/src/server/fieldAccess.js +33 -25
  10. package/src/server/jsonApiModule/actions.js +151 -548
  11. package/src/server/jsonApiModule/assistantExtension.js +386 -0
  12. package/src/server/jsonApiModule/customActionId.js +12 -0
  13. package/src/server/jsonApiModule/repository.js +73 -21
  14. package/src/server/jsonApiModule/routes.js +44 -30
  15. package/src/server/jsonApiModule/service.js +37 -35
  16. package/src/server/jsonApiResourceContract.js +22 -18
  17. package/src/server/listFilterJsonRest.js +304 -0
  18. package/src/server/listFilterTypes.js +427 -0
  19. package/src/server/listFilters.js +26 -722
  20. package/src/server/listQueryValidators.js +26 -21
  21. package/src/server/lookupPathSupport.js +31 -18
  22. package/src/server/lookups.js +20 -34
  23. package/src/server/normalizeOptionalText.js +13 -0
  24. package/src/server/repositorySupport.js +11 -10
  25. package/src/server/resourceRuntime/compiledRuntime.js +284 -0
  26. package/src/server/resourceRuntime/index.js +167 -920
  27. package/src/server/resourceRuntime/listControls.js +333 -0
  28. package/src/server/resourceRuntime/lookupHydration.js +121 -186
  29. package/src/server/resourceRuntime/operationStages.js +140 -0
  30. package/src/server/resourceRuntime/recordValidation.js +65 -0
  31. package/src/server/routeContracts.js +44 -46
  32. package/src/server/serviceEvents.js +42 -118
  33. package/src/server/serviceMethods.js +34 -26
  34. package/src/server/types.js +156 -0
  35. package/test/assistantActionConformance.test.js +8 -5
  36. package/test/assistantPagination.integration.test.js +5 -3
  37. package/test/createCrudServiceFromResource.test.js +0 -18
  38. package/test/customActionId.test.js +12 -0
  39. package/test/defineCrudJsonApiFeature.test.js +193 -28
  40. package/test/errorCodes.test.js +18 -0
  41. package/test/jsonApiRepository.test.js +103 -3
  42. package/test/listFilters.test.js +7 -7
  43. package/test/listQueryValidators.test.js +1 -54
  44. package/test/serviceEvents.test.js +31 -81
  45. package/test/support/crudJsonApiActionOptions.js +37 -0
  46. package/src/server/crudModuleConfig.js +0 -181
  47. package/src/server/lookupHydration.js +0 -710
  48. package/test/crudModuleConfig.test.js +0 -33
@@ -0,0 +1,140 @@
1
+ import { normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
2
+
3
+ /**
4
+ * Adds each virtual field's projection to a read query.
5
+ * @param {object} dbQuery
6
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
7
+ * @param {{ knex: import("@jskit-ai/database-runtime/server/types").RuntimeKnex, tableName: string }} projection
8
+ */
9
+ function applyCrudRepositoryVirtualProjections(dbQuery, runtime, { knex, tableName }) {
10
+ for (const virtualField of runtime.virtualFields) {
11
+ virtualField.applyProjection(dbQuery, {
12
+ knex,
13
+ tableName,
14
+ alias: virtualField.alias,
15
+ fieldKey: virtualField.key
16
+ });
17
+ }
18
+
19
+ return dbQuery;
20
+ }
21
+
22
+ /**
23
+ * Runs an operation's applyQuery stage, which the compiled runtime holds as a function or null.
24
+ * @param {object} dbQuery
25
+ * @param {Function | null | undefined} stage
26
+ * @param {object} stageContext
27
+ * @param {{ context: string, stageKey: string }} labels
28
+ */
29
+ function applyConfiguredQueryStage(dbQuery, stage, stageContext, { context, stageKey }) {
30
+ if (!stage) {
31
+ return {
32
+ queryBuilder: dbQuery
33
+ };
34
+ }
35
+
36
+ const directResult = stage(dbQuery, stageContext);
37
+ if (directResult === undefined || directResult === dbQuery) {
38
+ return {
39
+ queryBuilder: dbQuery
40
+ };
41
+ }
42
+
43
+ if (isCrudRepositoryQueryBuilder(directResult)) {
44
+ return {
45
+ queryBuilder: directResult
46
+ };
47
+ }
48
+
49
+ // readable-check: allow method-probe - data: an application's query stage may return a promise
50
+ if (directResult && typeof directResult.then === "function") {
51
+ return Promise.resolve(directResult).then((awaitedResult) => {
52
+ if (awaitedResult === undefined || awaitedResult === dbQuery) {
53
+ return {
54
+ queryBuilder: dbQuery
55
+ };
56
+ }
57
+
58
+ if (isCrudRepositoryQueryBuilder(awaitedResult)) {
59
+ throw new TypeError(
60
+ `${context} ${stageKey} cannot return a query builder asynchronously. Mutate the provided builder and return undefined instead.`
61
+ );
62
+ }
63
+
64
+ throw new TypeError(
65
+ `${context} ${stageKey} must return undefined, the provided query builder, or another query builder synchronously.`
66
+ );
67
+ });
68
+ }
69
+
70
+ return Promise.reject(new TypeError(
71
+ `${context} ${stageKey} must return undefined, the provided query builder, or another query builder synchronously.`
72
+ ));
73
+ }
74
+
75
+ function isCrudRepositoryQueryBuilder(value) {
76
+ if (!value || (typeof value !== "object" && typeof value !== "function") || Array.isArray(value)) {
77
+ return false;
78
+ }
79
+
80
+ return [
81
+ "where",
82
+ "whereIn",
83
+ "select",
84
+ "insert",
85
+ "update",
86
+ "delete",
87
+ "del",
88
+ "first",
89
+ "modify"
90
+ // readable-check: allow method-probe - platform object: a query stage's result is a query builder when it has one of its methods
91
+ ].some((key) => typeof value[key] === "function");
92
+ }
93
+
94
+ /**
95
+ * Runs an operation's payload stage, which the compiled runtime holds as a function or null.
96
+ * @param {object} payload
97
+ * @param {Function | null | undefined} stage
98
+ * @param {object} stageContext
99
+ * @param {{ context: string, stageKey: string }} labels
100
+ */
101
+ async function applyConfiguredObjectStage(payload, stage, stageContext, { context, stageKey }) {
102
+ const normalizedPayload = normalizeObject(payload);
103
+ if (!stage) {
104
+ return normalizedPayload;
105
+ }
106
+
107
+ const nextPayload = await stage(normalizedPayload, stageContext);
108
+ if (nextPayload === undefined) {
109
+ return normalizedPayload;
110
+ }
111
+
112
+ if (!nextPayload || typeof nextPayload !== "object" || Array.isArray(nextPayload)) {
113
+ throw new TypeError(`${context} ${stageKey} must return an object when it returns a value.`);
114
+ }
115
+
116
+ return nextPayload;
117
+ }
118
+
119
+ /**
120
+ * What every stage of one repository call receives besides its own values: the
121
+ * runtime, the repository options, the call's options and a state object the
122
+ * call's stages share.
123
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
124
+ * @param {object} callOptions
125
+ */
126
+ function buildCrudRepositoryActionContextBase(runtime, callOptions) {
127
+ return {
128
+ runtime,
129
+ repositoryOptions: runtime.repositoryOptions,
130
+ callOptions,
131
+ state: {}
132
+ };
133
+ }
134
+
135
+ export {
136
+ applyCrudRepositoryVirtualProjections,
137
+ applyConfiguredQueryStage,
138
+ applyConfiguredObjectStage,
139
+ buildCrudRepositoryActionContextBase
140
+ };
@@ -0,0 +1,65 @@
1
+ import { createValidationError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { normalizeObject } from "@jskit-ai/kernel/shared/support/normalize";
3
+ import { codedFieldErrors, errorFieldErrors, validateSchemaPayload } from "@jskit-ai/kernel/shared/validators";
4
+
5
+ /**
6
+ * A create or patch payload validated by the resource's body schema for it, when it has one.
7
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
8
+ * @param {object} payload
9
+ * @param {"create" | "patch"} operationKey
10
+ */
11
+ async function normalizeRepositoryInputPayload(runtime, payload, operationKey) {
12
+ const input = runtime.input[operationKey];
13
+ const normalizedPayload = normalizeObject(payload);
14
+
15
+ if (!input) {
16
+ return normalizedPayload;
17
+ }
18
+
19
+ try {
20
+ const nextPayload = validateSchemaPayload(input, normalizedPayload, {
21
+ phase: "input",
22
+ context: `${runtime.context} operations.${operationKey}.body`
23
+ });
24
+ return normalizeObject(nextPayload);
25
+ } catch (error) {
26
+ const fieldErrors = codedFieldErrors(error);
27
+ if (fieldErrors) {
28
+ throw createValidationError(fieldErrors);
29
+ }
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ /**
35
+ * A stored record validated by the resource's view output schema.
36
+ * @param {import("../types.js").CompiledCrudRepositoryRuntime} runtime
37
+ * @param {object} record
38
+ * @param {{ operation: string }} labels The operation its error names.
39
+ */
40
+ async function normalizeRepositoryOutputRecord(runtime, record, { operation }) {
41
+ try {
42
+ return validateSchemaPayload(runtime.output, record, {
43
+ phase: "output",
44
+ context: `${runtime.context} operations.view.output`
45
+ });
46
+ } catch (error) {
47
+ const fieldErrors = errorFieldErrors(error)?.fieldErrors;
48
+ if (fieldErrors) {
49
+ const detailMessage = Object.entries(fieldErrors)
50
+ .map(([field, message]) => `${field}: ${message}`)
51
+ .join(", ");
52
+ throw new TypeError(
53
+ `${runtime.context} ${operation} output validation failed: ${detailMessage}.`
54
+ );
55
+ }
56
+ throw new TypeError(
57
+ `${runtime.context} ${operation} output validation failed: ${String(error?.message || "Invalid value.")}.`
58
+ );
59
+ }
60
+ }
61
+
62
+ export {
63
+ normalizeRepositoryInputPayload,
64
+ normalizeRepositoryOutputRecord
65
+ };
@@ -12,11 +12,9 @@ import {
12
12
  listSearchQueryValidator as defaultListSearchQueryValidator,
13
13
  lookupIncludeQueryValidator as defaultLookupIncludeQueryValidator
14
14
  } from "./listQueryValidators.js";
15
- import { resolveJsonApiRelationshipEntries } from "./jsonApiResourceContract.js";
16
-
17
- function isRecord(value) {
18
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
19
- }
15
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
16
+ import { resolveDeclaredLookupContainerKey, resolveJsonApiRelationshipEntries } from "./jsonApiResourceContract.js";
17
+ import { normalizeOptionalText } from "./normalizeOptionalText.js";
20
18
 
21
19
  function readOwnValue(source = {}, key = "") {
22
20
  if (isRecord(source) && Object.hasOwn(source, key)) {
@@ -32,8 +30,8 @@ function readOwnValue(source = {}, key = "") {
32
30
  };
33
31
  }
34
32
 
35
- function resolveLookupContainer(record = {}, lookupContainerKey = "") {
36
- const normalizedLookupContainerKey = String(lookupContainerKey || "").trim();
33
+ function resolveLookupContainer(record, lookupContainerKey = "") {
34
+ const normalizedLookupContainerKey = normalizeText(lookupContainerKey);
37
35
  if (!normalizedLookupContainerKey || !isRecord(record?.[normalizedLookupContainerKey])) {
38
36
  return {};
39
37
  }
@@ -59,27 +57,18 @@ function resolveRelationshipValueSource(record = {}, entry = {}, {
59
57
  return recordValue.found ? recordValue : lookupValue;
60
58
  }
61
59
 
62
- function normalizeLookupId(value) {
63
- if (value == null) {
64
- return null;
65
- }
66
-
67
- const normalized = String(value).trim();
68
- return normalized || null;
69
- }
70
-
71
60
  function normalizeRelationshipIdentifierId(value = null) {
72
61
  if (isRecord(value)) {
73
62
  if (isRecord(value.data)) {
74
- return normalizeLookupId(value.data.id);
63
+ return normalizeOptionalText(value.data.id);
75
64
  }
76
- return normalizeLookupId(value.id);
65
+ return normalizeOptionalText(value.id);
77
66
  }
78
67
 
79
- return normalizeLookupId(value);
68
+ return normalizeOptionalText(value);
80
69
  }
81
70
 
82
- function createRelationshipIdentifier(entry = {}, value = null) {
71
+ function buildRelationshipIdentifier(entry = {}, value = null) {
83
72
  const id = normalizeRelationshipIdentifierId(value);
84
73
  if (!id) {
85
74
  return null;
@@ -97,12 +86,12 @@ function createRecordAttributesResolver(definition = null, {
97
86
  const relationshipEntries = resolveJsonApiRelationshipEntries(definition);
98
87
  const excludedKeys = new Set(
99
88
  relationshipEntries
100
- .map((entry) => String(entry.attributeKey || "").trim())
89
+ .map((entry) => normalizeText(entry.attributeKey))
101
90
  .filter(Boolean)
102
91
  );
103
92
 
104
93
  for (const key of excludeKeys) {
105
- const normalizedKey = String(key || "").trim();
94
+ const normalizedKey = normalizeText(key);
106
95
  if (normalizedKey) {
107
96
  excludedKeys.add(normalizedKey);
108
97
  }
@@ -157,14 +146,14 @@ function createRecordRelationshipsResolver(definition = null, {
157
146
  const items = Array.isArray(value) ? value : [];
158
147
  relationships[entry.relationshipName] = {
159
148
  data: items
160
- .map((item) => createRelationshipIdentifier(entry, item))
149
+ .map((item) => buildRelationshipIdentifier(entry, item))
161
150
  .filter(Boolean)
162
151
  };
163
152
  continue;
164
153
  }
165
154
 
166
155
  relationships[entry.relationshipName] = {
167
- data: createRelationshipIdentifier(entry, value)
156
+ data: buildRelationshipIdentifier(entry, value)
168
157
  };
169
158
  }
170
159
 
@@ -215,21 +204,17 @@ function createRequestRelationshipMapper(definition = null) {
215
204
  };
216
205
  }
217
206
 
218
- function resolveOutputAttributeExcludeKeys(resource = {}) {
219
- const lookupContainerKey = String(resource?.contract?.lookup?.containerKey || "").trim();
207
+ function resolveOutputAttributeExcludeKeys(resource) {
208
+ const lookupContainerKey = resolveDeclaredLookupContainerKey(resource);
220
209
  return lookupContainerKey ? Object.freeze([lookupContainerKey]) : Object.freeze([]);
221
210
  }
222
211
 
223
- function resolveLookupContainerKey(resource = {}) {
224
- return String(resource?.contract?.lookup?.containerKey || "").trim();
225
- }
226
-
227
212
  function normalizeIncludedLookupRecord(source = null, fallbackId = null) {
228
213
  if (!isRecord(source)) {
229
214
  return null;
230
215
  }
231
216
 
232
- const directId = normalizeLookupId(source.id);
217
+ const directId = normalizeOptionalText(source.id);
233
218
  if (directId) {
234
219
  return {
235
220
  id: directId,
@@ -237,19 +222,19 @@ function normalizeIncludedLookupRecord(source = null, fallbackId = null) {
237
222
  };
238
223
  }
239
224
 
240
- const preferredNestedRecord = normalizeLookupId(fallbackId) && isRecord(source[fallbackId])
225
+ const preferredNestedRecord = normalizeOptionalText(fallbackId) && isRecord(source[fallbackId])
241
226
  ? source[fallbackId]
242
227
  : null;
243
228
  if (preferredNestedRecord) {
244
229
  return {
245
- id: normalizeLookupId(preferredNestedRecord.id ?? fallbackId),
230
+ id: normalizeOptionalText(preferredNestedRecord.id ?? fallbackId),
246
231
  ...preferredNestedRecord
247
232
  };
248
233
  }
249
234
 
250
235
  const nestedEntries = Object.entries(source).filter(([, value]) => isRecord(value));
251
236
  if (nestedEntries.length !== 1) {
252
- const fallbackRecordId = normalizeLookupId(fallbackId);
237
+ const fallbackRecordId = normalizeOptionalText(fallbackId);
253
238
  if (!fallbackRecordId) {
254
239
  return null;
255
240
  }
@@ -261,7 +246,7 @@ function normalizeIncludedLookupRecord(source = null, fallbackId = null) {
261
246
  }
262
247
 
263
248
  const [nestedKey, nestedRecord] = nestedEntries[0];
264
- const nestedId = normalizeLookupId(nestedRecord.id ?? nestedKey ?? fallbackId);
249
+ const nestedId = normalizeOptionalText(nestedRecord.id ?? nestedKey ?? fallbackId);
265
250
  if (!nestedId) {
266
251
  return null;
267
252
  }
@@ -280,7 +265,7 @@ function appendIncludedRelationshipResource({
280
265
  fallbackId = null
281
266
  } = {}) {
282
267
  const normalizedLookupRecord = normalizeIncludedLookupRecord(lookupRecord, fallbackId);
283
- const includedId = normalizeLookupId(normalizedLookupRecord?.id ?? fallbackId);
268
+ const includedId = normalizeOptionalText(normalizedLookupRecord?.id ?? fallbackId);
284
269
  if (!normalizedLookupRecord || !includedId) {
285
270
  return;
286
271
  }
@@ -311,12 +296,12 @@ function createLookupIncludedResolver(definition = null, {
311
296
  lookupContainerKey = ""
312
297
  } = {}) {
313
298
  const relationshipEntries = resolveJsonApiRelationshipEntries(definition);
314
- const normalizedLookupContainerKey = String(lookupContainerKey || "").trim();
299
+ const normalizedLookupContainerKey = normalizeText(lookupContainerKey);
315
300
  if (!normalizedLookupContainerKey || relationshipEntries.length < 1) {
316
301
  return null;
317
302
  }
318
303
 
319
- return function getIncluded(payload = {}) {
304
+ return function getIncluded(payload) {
320
305
  const sourceRecords = Array.isArray(payload)
321
306
  ? payload
322
307
  : Array.isArray(payload?.items)
@@ -355,7 +340,7 @@ function createLookupIncludedResolver(definition = null, {
355
340
  continue;
356
341
  }
357
342
 
358
- const relationshipId = normalizeLookupId(record[entry.attributeKey]);
343
+ const relationshipId = normalizeOptionalText(record[entry.attributeKey]);
359
344
  const lookupRecord = sourceLookups[entry.attributeKey] ?? sourceLookups[entry.relationshipName];
360
345
  appendIncludedRelationshipResource({
361
346
  included,
@@ -371,13 +356,26 @@ function createLookupIncludedResolver(definition = null, {
371
356
  };
372
357
  }
373
358
 
359
+ /**
360
+ * The transport contracts of a CRUD resource's routes, derived from its definition and input schemas.
361
+ * @param {object} [options]
362
+ * @param {object} [options.resource]
363
+ * @param {object | null} [options.routeParamsValidator]
364
+ * @param {readonly string[]} [options.operations]
365
+ * @param {{ create?: object, update?: object }} [options.operationInputs]
366
+ * @param {object} [options.listSearchQueryValidator]
367
+ * @param {object} [options.lookupIncludeQueryValidator]
368
+ * @param {object | null} [options.listFilterQueryValidator]
369
+ */
374
370
  function createCrudJsonApiRouteContracts({
371
+ // readable-check: allow dependency-default - data: a resource definition
375
372
  resource = {},
376
373
  routeParamsValidator = null,
377
374
  operations = ["list", "view", "create", "update", "delete"],
378
375
  operationInputs = {},
379
376
  listSearchQueryValidator = defaultListSearchQueryValidator,
380
377
  lookupIncludeQueryValidator = defaultLookupIncludeQueryValidator,
378
+ // readable-check: allow dependency-default - data: an optional input schema
381
379
  listFilterQueryValidator = null
382
380
  } = {}) {
383
381
  const enabledOperations = new Set(operations);
@@ -400,14 +398,14 @@ function createCrudJsonApiRouteContracts({
400
398
  recordIdParamsValidator
401
399
  ])
402
400
  : recordIdParamsValidator;
403
- const routeType = resource?.namespace;
404
- const viewOutput = resource?.operations?.view?.output;
405
- const createBody = operationInputs.create || resource?.operations?.create?.body;
406
- const createOutput = resource?.operations?.create?.output;
407
- const patchBody = operationInputs.update || resource?.operations?.patch?.body;
408
- const patchOutput = resource?.operations?.patch?.output;
401
+ const routeType = resource.namespace;
402
+ const viewOutput = resource.operations?.view?.output;
403
+ const createBody = operationInputs.create || resource.operations?.create?.body;
404
+ const createOutput = resource.operations?.create?.output;
405
+ const patchBody = operationInputs.update || resource.operations?.patch?.body;
406
+ const patchOutput = resource.operations?.patch?.output;
409
407
  const outputAttributeExcludeKeys = resolveOutputAttributeExcludeKeys(resource);
410
- const lookupContainerKey = resolveLookupContainerKey(resource);
408
+ const lookupContainerKey = resolveDeclaredLookupContainerKey(resource);
411
409
  const viewOutputRelationships = resolveJsonApiRelationshipEntries(viewOutput);
412
410
  const createBodyRelationships = resolveJsonApiRelationshipEntries(createBody);
413
411
  const createOutputRelationships = resolveJsonApiRelationshipEntries(createOutput);
@@ -1,124 +1,48 @@
1
- import {
2
- requireCrudNamespace,
3
- resolveCrudRecordChangedEvent
4
- } from "@jskit-ai/resource-crud-core/shared/crudNamespaceSupport";
5
-
6
- function normalizeCrudEventEntityId(value = null) {
7
- return value == null ? "" : String(value).trim();
8
- }
9
-
10
- function resolveCrudEntityIdFromResult({ result } = {}) {
11
- return normalizeCrudEventEntityId(result?.id);
12
- }
13
-
1
+ import { isJsonApiDataResult, isJsonApiDocumentResult } from "@jskit-ai/http-runtime/shared";
2
+ import { createEntityChangedActionEvent } from "@jskit-ai/kernel/server/actions";
3
+ import { resolveCrudRecordChangedEvent } from "@jskit-ai/resource-crud-core/shared/crudNamespaceSupport";
4
+
5
+ /**
6
+ * The created record's id, for a create event, from the tagged JSON:API result
7
+ * the action or service returned: a document result's `value.data.id`
8
+ * (returnJsonApiDocument, what a CRUD service's createDocument returns) or a
9
+ * data result's record `value.id` (returnJsonApiData(record), whose id the
10
+ * HTTP route transport reads the same way). "" for anything else.
11
+ * @param {{ result?: unknown }} [execution]
12
+ */
14
13
  function resolveCrudJsonApiEntityIdFromResult({ result } = {}) {
15
- return normalizeCrudEventEntityId(result?.data?.id ?? result?.value?.data?.id);
16
- }
17
-
18
- function resolveCrudEntityIdFromArgs({ args = [] } = {}) {
19
- return normalizeCrudEventEntityId(args[0]);
14
+ let id = null;
15
+ if (isJsonApiDocumentResult(result)) {
16
+ // data: a document result's data may be null
17
+ id = result.value?.data?.id;
18
+ } else if (isJsonApiDataResult(result)) {
19
+ // data: a data result's record may be null
20
+ id = result.value?.id;
21
+ }
22
+ return id == null ? "" : String(id).trim();
20
23
  }
21
24
 
22
- function createCrudServiceEvents(resource = {}, { context = "crudService" } = {}) {
23
- const namespace = requireCrudNamespace(resource?.namespace, { context: `${context} resource.namespace` });
24
- const recordChangedEventName = resolveCrudRecordChangedEvent(namespace);
25
-
26
- return Object.freeze({
27
- createRecord: Object.freeze([
28
- Object.freeze({
29
- type: "entity.changed",
30
- source: "crud",
31
- entity: "record",
32
- operation: "created",
33
- entityId: resolveCrudEntityIdFromResult,
34
- realtime: Object.freeze({
35
- event: recordChangedEventName,
36
- audience: "event_scope"
37
- })
38
- })
39
- ]),
40
- updateRecord: Object.freeze([
41
- Object.freeze({
42
- type: "entity.changed",
43
- source: "crud",
44
- entity: "record",
45
- operation: "updated",
46
- entityId: resolveCrudEntityIdFromResult,
47
- realtime: Object.freeze({
48
- event: recordChangedEventName,
49
- audience: "event_scope"
50
- })
51
- })
52
- ]),
53
- deleteRecord: Object.freeze([
54
- Object.freeze({
55
- type: "entity.changed",
56
- source: "crud",
57
- entity: "record",
58
- operation: "deleted",
59
- entityId: resolveCrudEntityIdFromResult,
60
- realtime: Object.freeze({
61
- event: recordChangedEventName,
62
- audience: "event_scope"
63
- })
64
- })
65
- ])
66
- });
67
- }
68
-
69
- function createCrudJsonApiServiceEvents(namespace = "", { context = "createCrudJsonApiServiceEvents" } = {}) {
70
- const normalizedNamespace = requireCrudNamespace(namespace, {
71
- context: `${context} namespace`
72
- });
73
- const recordChangedEventName = resolveCrudRecordChangedEvent(normalizedNamespace);
74
-
75
- return Object.freeze({
76
- createDocument: Object.freeze([
77
- Object.freeze({
78
- type: "entity.changed",
79
- source: "crud",
80
- entity: "record",
81
- operation: "created",
82
- entityId: resolveCrudJsonApiEntityIdFromResult,
83
- realtime: Object.freeze({
84
- event: recordChangedEventName,
85
- audience: "event_scope"
86
- })
87
- })
88
- ]),
89
- patchDocumentById: Object.freeze([
90
- Object.freeze({
91
- type: "entity.changed",
92
- source: "crud",
93
- entity: "record",
94
- operation: "updated",
95
- entityId: resolveCrudEntityIdFromArgs,
96
- realtime: Object.freeze({
97
- event: recordChangedEventName,
98
- audience: "event_scope"
99
- })
100
- })
101
- ]),
102
- deleteDocumentById: Object.freeze([
103
- Object.freeze({
104
- type: "entity.changed",
105
- source: "crud",
106
- entity: "record",
107
- operation: "deleted",
108
- entityId: resolveCrudEntityIdFromArgs,
109
- realtime: Object.freeze({
110
- event: recordChangedEventName,
111
- audience: "event_scope"
112
- })
113
- })
114
- ])
25
+ /**
26
+ * The action event a CRUD record mutation announces: an entity change of the "crud" source's "record", published
27
+ * in realtime as the namespace's record-changed event (`<namespace>.record.changed`) to the audience. operation and
28
+ * entityId may be functions of the action's execution, as createEntityChangedActionEvent takes them.
29
+ * @param {object} change
30
+ * @param {string} change.namespace The CRUD resource's namespace.
31
+ * @param {string | ((execution: any) => string)} change.operation "created", "updated" or "deleted".
32
+ * @param {unknown} change.entityId
33
+ * @param {unknown} [change.audience] The realtime audience; the kernel's default when absent.
34
+ */
35
+ function buildCrudRecordChangedEvent({ namespace, operation, entityId, audience }) {
36
+ return createEntityChangedActionEvent({
37
+ source: "crud",
38
+ entity: "record",
39
+ operation,
40
+ entityId,
41
+ realtime: {
42
+ event: resolveCrudRecordChangedEvent(namespace),
43
+ audience
44
+ }
115
45
  });
116
46
  }
117
47
 
118
- export {
119
- createCrudServiceEvents,
120
- createCrudJsonApiServiceEvents,
121
- resolveCrudEntityIdFromArgs,
122
- resolveCrudEntityIdFromResult,
123
- resolveCrudJsonApiEntityIdFromResult
124
- };
48
+ export { buildCrudRecordChangedEvent, resolveCrudJsonApiEntityIdFromResult };