@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,333 @@
1
+ import { AppError } from "@jskit-ai/kernel/server/runtime/errors";
2
+ import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
3
+ import {
4
+ DEFAULT_LIST_LIMIT,
5
+ MAX_LIST_LIMIT,
6
+ normalizeCrudListLimit
7
+ } from "../repositorySupport.js";
8
+
9
+ const LIST_ORDER_DIRECTION_ASC = "asc";
10
+ const LIST_ORDER_DIRECTION_DESC = "desc";
11
+ const LIST_ORDER_NULLS_FIRST = "first";
12
+ const LIST_ORDER_NULLS_LAST = "last";
13
+ const ORDERED_LIST_CURSOR_VALUE_TYPE_KEY = "__jskitCursorValueType";
14
+ const ORDERED_LIST_CURSOR_VALUE_KEY = "value";
15
+ const ORDERED_LIST_CURSOR_VALUE_TYPE_DATE = "date";
16
+
17
+ /**
18
+ * @param {unknown} searchColumns The list options' searchColumns, when given.
19
+ * @param {readonly string[]} fallbackColumns The resource's string columns.
20
+ */
21
+ function normalizeSearchColumns(searchColumns, fallbackColumns) {
22
+ const normalizedConfiguredColumns = (Array.isArray(searchColumns) ? searchColumns : [])
23
+ .map((columnName) => normalizeText(columnName))
24
+ .filter(Boolean);
25
+
26
+ if (normalizedConfiguredColumns.length > 0) {
27
+ return Object.freeze([...new Set(normalizedConfiguredColumns)]);
28
+ }
29
+
30
+ return fallbackColumns;
31
+ }
32
+
33
+ function normalizeListOrderDirection(value = LIST_ORDER_DIRECTION_ASC) {
34
+ const normalized = normalizeText(value).toLowerCase();
35
+ if (!normalized) {
36
+ return LIST_ORDER_DIRECTION_ASC;
37
+ }
38
+ if (normalized === LIST_ORDER_DIRECTION_ASC || normalized === LIST_ORDER_DIRECTION_DESC) {
39
+ return normalized;
40
+ }
41
+
42
+ throw new TypeError(`crudRepository list.orderBy direction must be "${LIST_ORDER_DIRECTION_ASC}" or "${LIST_ORDER_DIRECTION_DESC}".`);
43
+ }
44
+
45
+ function normalizeListOrderNulls(value = LIST_ORDER_NULLS_LAST) {
46
+ const normalized = normalizeText(value).toLowerCase();
47
+ if (!normalized) {
48
+ return LIST_ORDER_NULLS_LAST;
49
+ }
50
+ if (normalized === LIST_ORDER_NULLS_FIRST || normalized === LIST_ORDER_NULLS_LAST) {
51
+ return normalized;
52
+ }
53
+
54
+ throw new TypeError(`crudRepository list.orderBy nulls must be "${LIST_ORDER_NULLS_FIRST}" or "${LIST_ORDER_NULLS_LAST}".`);
55
+ }
56
+
57
+ function normalizeListOrderBy(orderBy, { idColumn }) {
58
+ const sourceEntries = Array.isArray(orderBy)
59
+ ? orderBy
60
+ : orderBy === null || orderBy === undefined
61
+ ? []
62
+ : [orderBy];
63
+ const normalizedOrderBy = [];
64
+ const seenColumns = new Set();
65
+
66
+ for (const rawEntry of sourceEntries) {
67
+ const sourceEntry = typeof rawEntry === "string"
68
+ ? { column: rawEntry }
69
+ : rawEntry;
70
+ if (!isRecord(sourceEntry)) {
71
+ throw new TypeError("crudRepository list.orderBy entries must be objects or column strings.");
72
+ }
73
+
74
+ const column = normalizeText(sourceEntry.column);
75
+ if (!column) {
76
+ throw new TypeError("crudRepository list.orderBy entries require column.");
77
+ }
78
+ if (seenColumns.has(column)) {
79
+ continue;
80
+ }
81
+
82
+ seenColumns.add(column);
83
+ normalizedOrderBy.push(
84
+ Object.freeze({
85
+ column,
86
+ direction: normalizeListOrderDirection(sourceEntry.direction),
87
+ nulls: normalizeListOrderNulls(sourceEntry.nulls)
88
+ })
89
+ );
90
+ }
91
+
92
+ if (normalizedOrderBy.length > 0 && !seenColumns.has(idColumn)) {
93
+ normalizedOrderBy.push(
94
+ Object.freeze({
95
+ column: idColumn,
96
+ direction: normalizedOrderBy[normalizedOrderBy.length - 1].direction,
97
+ nulls: LIST_ORDER_NULLS_LAST
98
+ })
99
+ );
100
+ }
101
+
102
+ return Object.freeze(normalizedOrderBy);
103
+ }
104
+
105
+ /**
106
+ * A repository's list controls, from its list options: the default and maximum
107
+ * page size, the search columns and the order.
108
+ * @param {object} list The repository options' list, when given.
109
+ * @param {readonly string[]} fallbackSearchColumns
110
+ * @param {{ idColumn: string }} keys The id column that breaks order ties.
111
+ */
112
+ function resolveListRuntimeConfig(list = {}, fallbackSearchColumns, { idColumn }) {
113
+ const parsedMaxLimit = Number(list.maxLimit);
114
+ const normalizedMaxLimit = Number.isInteger(parsedMaxLimit) && parsedMaxLimit > 0
115
+ ? parsedMaxLimit
116
+ : MAX_LIST_LIMIT;
117
+ const normalizedDefaultLimit = normalizeCrudListLimit(list.defaultLimit, {
118
+ fallback: DEFAULT_LIST_LIMIT,
119
+ max: normalizedMaxLimit
120
+ });
121
+
122
+ return Object.freeze({
123
+ defaultLimit: normalizedDefaultLimit,
124
+ maxLimit: normalizedMaxLimit,
125
+ searchColumns: normalizeSearchColumns(list.searchColumns, fallbackSearchColumns),
126
+ orderBy: normalizeListOrderBy(list.orderBy, { idColumn })
127
+ });
128
+ }
129
+
130
+ function encodeOrderedListCursorValue(value = null) {
131
+ if (value instanceof Date) {
132
+ return {
133
+ [ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]: ORDERED_LIST_CURSOR_VALUE_TYPE_DATE,
134
+ [ORDERED_LIST_CURSOR_VALUE_KEY]: value.toISOString()
135
+ };
136
+ }
137
+
138
+ return value === undefined ? null : value;
139
+ }
140
+
141
+ function decodeOrderedListCursorValue(value = null) {
142
+ if (!isRecord(value)) {
143
+ return value === undefined ? null : value;
144
+ }
145
+
146
+ const valueType = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_TYPE_KEY]).toLowerCase();
147
+ if (!valueType) {
148
+ return value;
149
+ }
150
+ if (valueType !== ORDERED_LIST_CURSOR_VALUE_TYPE_DATE) {
151
+ return value;
152
+ }
153
+
154
+ const normalizedValue = normalizeText(value[ORDERED_LIST_CURSOR_VALUE_KEY]);
155
+ if (!normalizedValue) {
156
+ throw new TypeError("Ordered list cursor date values require a non-empty value.");
157
+ }
158
+
159
+ const date = new Date(normalizedValue);
160
+ if (Number.isNaN(date.getTime())) {
161
+ throw new TypeError("Ordered list cursor date values must be valid dates.");
162
+ }
163
+
164
+ return date;
165
+ }
166
+
167
+ /**
168
+ * @param {unknown} row
169
+ * @param {ReadonlyArray<{ column: string }>} orderBy The runtime's list order.
170
+ */
171
+ function encodeOrderedListCursor(row, orderBy) {
172
+ if (!isRecord(row) || orderBy.length < 1) {
173
+ return null;
174
+ }
175
+
176
+ const values = orderBy.map(({ column }) => (
177
+ Object.hasOwn(row, column) && row[column] !== undefined
178
+ ? encodeOrderedListCursorValue(row[column])
179
+ : null
180
+ ));
181
+
182
+ return Buffer.from(JSON.stringify({ values }), "utf8").toString("base64url");
183
+ }
184
+
185
+ function decodeOrderedListCursor(cursor, orderBy) {
186
+ const normalizedCursor = normalizeText(cursor);
187
+ if (!normalizedCursor || orderBy.length < 1) {
188
+ return null;
189
+ }
190
+
191
+ try {
192
+ const decoded = Buffer.from(normalizedCursor, "base64url").toString("utf8");
193
+ const payload = JSON.parse(decoded);
194
+ const values = Array.isArray(payload?.values) ? payload.values : null;
195
+ if (!values || values.length !== orderBy.length) {
196
+ throw new AppError(400, "Invalid cursor.", {
197
+ code: "INVALID_CURSOR"
198
+ });
199
+ }
200
+
201
+ return values.map((value) => decodeOrderedListCursorValue(value));
202
+ } catch (error) {
203
+ if (error instanceof AppError) {
204
+ throw error;
205
+ }
206
+
207
+ throw new AppError(400, "Invalid cursor.", {
208
+ code: "INVALID_CURSOR"
209
+ });
210
+ }
211
+ }
212
+
213
+ function applyOrderedListCursorEquality(query, descriptor = {}, value = null) {
214
+ if (value === null) {
215
+ query.whereNull(descriptor.column);
216
+ return;
217
+ }
218
+
219
+ query.where(descriptor.column, value);
220
+ }
221
+
222
+ function applyOrderedListCursorAfterBranch(query, descriptor = {}, value = null) {
223
+ const operator = descriptor.direction === LIST_ORDER_DIRECTION_DESC ? "<" : ">";
224
+
225
+ if (value === null) {
226
+ if (descriptor.nulls === LIST_ORDER_NULLS_FIRST) {
227
+ query.whereNotNull(descriptor.column);
228
+ return true;
229
+ }
230
+
231
+ return false;
232
+ }
233
+
234
+ if (descriptor.nulls === LIST_ORDER_NULLS_LAST) {
235
+ query.where((branchQuery) => {
236
+ branchQuery.where(descriptor.column, operator, value);
237
+ branchQuery.orWhereNull(descriptor.column);
238
+ });
239
+ return true;
240
+ }
241
+
242
+ query.where(descriptor.column, operator, value);
243
+ return true;
244
+ }
245
+
246
+ function canApplyOrderedListCursorAfterBranch(descriptor = {}, value = null) {
247
+ return !(value === null && descriptor.nulls === LIST_ORDER_NULLS_LAST);
248
+ }
249
+
250
+ function appendOrderedListCursorBranches(query, orderBy = [], cursorValues = [], index = 0, { useOr = false } = {}) {
251
+ const descriptor = orderBy[index];
252
+ if (!descriptor) {
253
+ return false;
254
+ }
255
+
256
+ let addedBranch = false;
257
+ const currentValue = cursorValues[index] ?? null;
258
+
259
+ if (canApplyOrderedListCursorAfterBranch(descriptor, currentValue)) {
260
+ const afterMethod = useOr === true ? "orWhere" : "where";
261
+ query[afterMethod]((afterQuery) => {
262
+ applyOrderedListCursorAfterBranch(afterQuery, descriptor, currentValue);
263
+ });
264
+ addedBranch = true;
265
+ }
266
+
267
+ if (index >= orderBy.length - 1) {
268
+ return addedBranch;
269
+ }
270
+
271
+ const equalityMethod = useOr === true || addedBranch === true ? "orWhere" : "where";
272
+ query[equalityMethod]((equalQuery) => {
273
+ applyOrderedListCursorEquality(equalQuery, descriptor, currentValue);
274
+ equalQuery.where((nestedQuery) => {
275
+ appendOrderedListCursorBranches(nestedQuery, orderBy, cursorValues, index + 1);
276
+ });
277
+ });
278
+ return true;
279
+ }
280
+
281
+ /**
282
+ * @param {object} query
283
+ * @param {{ orderBy: ReadonlyArray<object>, cursor: unknown }} list The runtime's list order and the query's cursor.
284
+ */
285
+ function applyOrderedListCursorFilter(query, { orderBy, cursor }) {
286
+ const cursorValues = decodeOrderedListCursor(cursor, orderBy);
287
+ if (!cursorValues) {
288
+ return query;
289
+ }
290
+
291
+ return query.where((cursorQuery) => {
292
+ appendOrderedListCursorBranches(cursorQuery, orderBy, cursorValues);
293
+ });
294
+ }
295
+
296
+ function applyOrderedListControls(dbQuery, orderBy) {
297
+ let nextQuery = dbQuery;
298
+ for (const descriptor of orderBy) {
299
+ nextQuery = nextQuery.orderByRaw(
300
+ descriptor.nulls === LIST_ORDER_NULLS_FIRST
301
+ ? "?? is null desc"
302
+ : "?? is null asc",
303
+ [descriptor.column]
304
+ );
305
+ nextQuery = nextQuery.orderBy(descriptor.column, descriptor.direction);
306
+ }
307
+
308
+ return nextQuery;
309
+ }
310
+
311
+ /**
312
+ * @param {object} dbQuery
313
+ * @param {{ idColumn: string, limit: number, orderBy: ReadonlyArray<object> }} controls
314
+ */
315
+ function enforceCrudRepositoryListControls(dbQuery, { idColumn, limit, orderBy }) {
316
+ const nextQuery = dbQuery.clearOrder().clear("limit");
317
+
318
+ if (orderBy.length > 0) {
319
+ return applyOrderedListControls(nextQuery, orderBy)
320
+ .limit(limit);
321
+ }
322
+
323
+ return nextQuery
324
+ .orderBy(idColumn, "asc")
325
+ .limit(limit);
326
+ }
327
+
328
+ export {
329
+ resolveListRuntimeConfig,
330
+ encodeOrderedListCursor,
331
+ applyOrderedListCursorFilter,
332
+ enforceCrudRepositoryListControls
333
+ };