@jskit-ai/crud-core 0.2.26 → 0.2.28
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 +2 -0
- package/package.json +6 -6
- package/patterns/crud-feature-package/PATTERN.md +2 -1
- package/patterns/crud-feature-package/example/packages/books/package.json +3 -3
- package/src/server/jsonApiModule/actions.js +10 -10
- package/src/server/listFilterJsonRest.js +91 -80
- package/src/server/listFilters.js +10 -14
- package/src/server/listQueryValidators.js +4 -3
- package/test/assistantActionConformance.test.js +80 -7
- package/test/listFilterRoutes.test.js +60 -8
- package/test/listFilters.test.js +34 -0
- package/test/nestedIncludeFieldsets.test.js +83 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
- A `date`, `dateRange` or `numberRange` list filter with a custom `apply` filters a list whose service passes its query through `toJsonRestQuery` (step 5 of the structured-filters guide), where json-rest-api refused the list with 422 "Field not allowed": its search schema entry (`jsonRestSearchSchema`) takes the filter's own key, but `toJsonRestQuery` sent the internal bound keys of a range filter without one (`__jskit_<key>_from` and `__jskit_<key>_toExclusive`, or `_min` and `_max`). It now sends such a filter under its own key with its parsed value, a day, `{ from, to }` or `{ min, max }`, which json-rest-api hands the `apply` as `applyQuery` does. Each filter's search schema entries and the values `toJsonRestQuery` sends for it now come from one place, so a list sends only keys its search schema declares, for every filter type with or without an `apply`; range filters without one keep their bound keys. Tests list orders over HTTP through such filters and check every type.
|
|
6
|
+
- A CRUD list or view whose includes reach below their first level refuses a `fields` key that is a relationship alias, or that names no type it shows, as it did before 0.2.26 and as a contract whose includes stop at their first level does: 400 `ACTION_VALIDATION_FAILED` naming `fields.<key>`, with the allowed types and the type to use for each alias (`crud.query.fieldsKeysInvalidWithAliases`), before the action runs. Since 0.2.26 the list and view actions checked such keys inside `execute` and threw kernel's `createValidationError` (`validation_failed`), so an assistant tool calling the list with `fields: { pet: [...] }` was told only "Validation failed.", without the field or the type to use, and the generated action registered with another `execute` (as a test stubs it) took the key. The check (`createIncludedFieldsetsCheck`) is now the actions' `checkInput`, which the kernel's action pipeline runs right after the input schema; its `crud.query.fieldsNotShown` refusal is answered the same way, and a fieldset for a type the includes reach still narrows it.
|
|
5
7
|
- A CRUD list over HTTP takes a filter that holds several values (`recordIdMany`, `enumMany`, and the list's `id`) as one comma-separated value too, `filter[customer]=1,2`, the form JSON:API gives a list, where the route's query validation refused it with 400 before the filter could split it (since 0.2.46 the filter reads `1,2` as `["1", "2"]`, but only a value the client named twice reached it in that form). Each entry must still be valid: `filter[customer]=1,,2` or a value the filter does not offer still answers 400.
|
|
6
8
|
- A `recordIdMany` list filter's search schema entry (`jsonRestSearchSchema`) takes `{ type: "id" }` items, where its items were a JSON Schema `anyOf`, which json-rest-schema refuses: a list asked for such a filter (`filter[customer]=1&filter[customer]=2`) answered 500 instead of the rows of those ids. `listFilterRoutes.test.js` lists orders by customer over HTTP.
|
|
7
9
|
- A CRUD list asked over HTTP with a `dateRange` or `numberRange` filter (`filter[arrival]=2026-03-01..2026-03-31`, `filter[total]=15..35`) answers exactly the rows inside the range, where it answered 400: the list action read the route's parsed `{ from, to }` again and refused it (`@jskit-ai/resource-crud-core` now takes it), and past that `toJsonRestQuery` dropped it. A malformed range still answers 400. A `date` or `dateRange` filter's search keys (`__jskit_<key>_from`, `__jskit_<key>_toExclusive`) now hold the day's start as ISO 8601 in UTC (`2026-03-01T00:00:00.000Z`, was `2026-03-01 00:00:00`), the form json-rest-api's `dateTime` search keys take: the old form was refused with 422, so a date filter never filtered through `jsonRestSearchSchema`. `listFilterRoutes.test.js` lists orders over HTTP through a filter contract's route and action validators, search schema and `toJsonRestQuery`, on SQLite.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jskit-ai/crud-core",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.28",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=24.0.0"
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"./locales/en.json": "./locales/en.json"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@jskit-ai/resource-core": "0.1.
|
|
24
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
23
|
+
"@jskit-ai/resource-core": "0.1.211",
|
|
24
|
+
"@jskit-ai/resource-crud-core": "0.1.213",
|
|
25
25
|
"json-rest-api": "3.1.4",
|
|
26
26
|
"json-rest-schema": "^1.0.20"
|
|
27
27
|
},
|
|
@@ -49,8 +49,8 @@
|
|
|
49
49
|
}
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
|
-
"@jskit-ai/http-runtime": "0.2.
|
|
53
|
-
"@jskit-ai/kernel": "0.2.
|
|
54
|
-
"@jskit-ai/resource-runtime": "0.2.
|
|
52
|
+
"@jskit-ai/http-runtime": "0.2.20",
|
|
53
|
+
"@jskit-ai/kernel": "0.2.20",
|
|
54
|
+
"@jskit-ai/resource-runtime": "0.2.25"
|
|
55
55
|
}
|
|
56
56
|
}
|
|
@@ -132,7 +132,8 @@ so an action without an HTTP route would otherwise reach records that no route
|
|
|
132
132
|
shows the user. The actions of an `internal: true` or `routes: false` feature
|
|
133
133
|
therefore stay off `automation` (the assistant cannot call them) unless their
|
|
134
134
|
permission names a permission (`require: "all"` or `"any"`), as the workspace
|
|
135
|
-
scope's default `crud.<namespace>.<operation>` permissions do
|
|
135
|
+
scope's default `crud.<namespace>.<operation>` permissions do (the operation is
|
|
136
|
+
`list`, `view`, `create`, `update` or `delete`; an HTTP `PATCH` is `update`). Give such a
|
|
136
137
|
feature explicit `permissions` when the assistant should read it for the users
|
|
137
138
|
who hold them; the default for other surfaces, `require: "authenticated"`,
|
|
138
139
|
would admit every signed-in user. An additional action's own `channels`
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
"./shared": "./src/shared/index.js"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@jskit-ai/crud-core": "0.2.
|
|
13
|
-
"@jskit-ai/resource-core": "0.1.
|
|
14
|
-
"@jskit-ai/resource-crud-core": "0.1.
|
|
12
|
+
"@jskit-ai/crud-core": "0.2.28",
|
|
13
|
+
"@jskit-ai/resource-core": "0.1.211",
|
|
14
|
+
"@jskit-ai/resource-crud-core": "0.1.213"
|
|
15
15
|
},
|
|
16
16
|
"jskit": {
|
|
17
17
|
"kind": "runtime",
|
|
@@ -36,8 +36,9 @@ function resolveCrudActionChannels(permission, servedOverHttp) {
|
|
|
36
36
|
|
|
37
37
|
function buildActionInput(resource, operation, scopeInputValidator, listFilterQueryValidator, operationInputs) {
|
|
38
38
|
const definitions = scopeInputValidator ? [scopeInputValidator] : [];
|
|
39
|
-
// A fieldset for a type the includes reach below their first level is checked
|
|
40
|
-
// createIncludedFieldsetsCheck): only the tables they cross name that type, and every feature owns its
|
|
39
|
+
// A fieldset for a type the includes reach below their first level is checked by the action's checkInput, after this
|
|
40
|
+
// schema (see createIncludedFieldsetsCheck): only the tables they cross name that type, and every feature owns its
|
|
41
|
+
// tables at boot.
|
|
41
42
|
if (operation === "list") {
|
|
42
43
|
definitions.push(...createStandardCrudListQueryValidators({
|
|
43
44
|
resource,
|
|
@@ -264,6 +265,8 @@ function createCrudJsonApiActions({
|
|
|
264
265
|
}) {
|
|
265
266
|
const definitions = builtDefinitions ?? createCrudJsonApiActionDefinitions({ namespace, resource, ...definitionOptions });
|
|
266
267
|
const checkIncludedFieldsets = createIncludedFieldsetsCheck(resource);
|
|
268
|
+
// A read's input refuses a fieldset for a type its includes do not show, as its schema refuses any other bad key.
|
|
269
|
+
const checkReadInput = (input) => checkIncludedFieldsets(input.fields, includedTypes());
|
|
267
270
|
const mutationEvent = (operation, entityId) => buildCrudRecordChangedEvent({
|
|
268
271
|
namespace,
|
|
269
272
|
operation,
|
|
@@ -378,19 +381,15 @@ function createCrudJsonApiActions({
|
|
|
378
381
|
operation: "list",
|
|
379
382
|
kind: "query",
|
|
380
383
|
events: [],
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
return executeOperation("list", input, context, listDocuments);
|
|
384
|
-
}
|
|
384
|
+
checkInput: checkReadInput,
|
|
385
|
+
execute: (input, context) => executeOperation("list", input, context, listDocuments)
|
|
385
386
|
},
|
|
386
387
|
{
|
|
387
388
|
operation: "view",
|
|
388
389
|
kind: "query",
|
|
389
390
|
events: [],
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
return executeOperation("view", input, context, viewDocument);
|
|
393
|
-
}
|
|
391
|
+
checkInput: checkReadInput,
|
|
392
|
+
execute: (input, context) => executeOperation("view", input, context, viewDocument)
|
|
394
393
|
},
|
|
395
394
|
{
|
|
396
395
|
operation: "create",
|
|
@@ -425,6 +424,7 @@ function createCrudJsonApiActions({
|
|
|
425
424
|
output: null,
|
|
426
425
|
extensions: built.extensions,
|
|
427
426
|
events: definition.events,
|
|
427
|
+
...(definition.checkInput ? { checkInput: definition.checkInput } : {}),
|
|
428
428
|
execute: definition.execute
|
|
429
429
|
});
|
|
430
430
|
});
|
|
@@ -195,115 +195,126 @@ function resolveCrudListFilterEntries(value = {}) {
|
|
|
195
195
|
return Object.values(defineCrudListFilters(value));
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
function createCrudListFilterJsonRestSearchSchema(runtime = {}, { columns = {}, apply = {} } = {}) {
|
|
199
|
-
const filterEntries = resolveCrudListFilterEntries(runtime);
|
|
200
|
-
const normalizedColumns = normalizeColumnsMap(columns);
|
|
201
|
-
const schema = {};
|
|
202
|
-
|
|
203
|
-
for (const filter of filterEntries) {
|
|
204
|
-
// readable-check: allow method-probe - input validation: apply holds an application's optional custom filters; other filters use the default
|
|
205
|
-
const customApply = typeof apply[filter.key] === "function" ? apply[filter.key] : null;
|
|
206
|
-
if (customApply) {
|
|
207
|
-
schema[filter.queryKey] = buildJsonRestCustomFilterSearchSchemaEntry(filter, customApply);
|
|
208
|
-
continue;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
const actualField = resolveJsonRestFilterActualField(filter, normalizedColumns);
|
|
212
|
-
if (!actualField) {
|
|
213
|
-
continue;
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const simpleEntry = buildJsonRestSimpleFilterSearchSchemaEntry(filter, { actualField });
|
|
217
|
-
if (simpleEntry) {
|
|
218
|
-
schema[filter.queryKey] = simpleEntry;
|
|
219
|
-
continue;
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
if (filter.type === CRUD_LIST_FILTER_TYPE_PRESENCE) {
|
|
223
|
-
schema[filter.queryKey] = buildJsonRestPresenceFilterSearchSchemaEntry(filter, { actualField });
|
|
224
|
-
continue;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
Object.assign(schema, buildJsonRestRangeFilterSearchSchemaEntries(filter, { actualField }));
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
return Object.freeze(schema);
|
|
231
|
-
}
|
|
232
|
-
|
|
233
198
|
// The instant a filter's day starts, in the form json-rest-api's dateTime search keys take (ISO 8601 with its zone,
|
|
234
199
|
// which refuses "2026-03-01 00:00:00"): midnight UTC, the zone a dateTime is stored in.
|
|
235
200
|
function dateFilterDayStart(date) {
|
|
236
201
|
return `${date}T00:00:00.000Z`;
|
|
237
202
|
}
|
|
238
203
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
function addJsonRestFilterValue(target = {}, filter = {}, value) {
|
|
250
|
-
if (filter.type === CRUD_LIST_FILTER_TYPE_DATE) {
|
|
251
|
-
addJsonRestDateFilterValues(target, filter, value);
|
|
252
|
-
return;
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
if (filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
|
|
256
|
-
if (value?.from) {
|
|
257
|
-
target[renderInternalJsonRestFilterKey(filter, "from")] = dateFilterDayStart(value.from);
|
|
204
|
+
// The internal bound keys a range filter without a custom apply sends for its parsed value: a date's day, or a
|
|
205
|
+
// dateRange's days, as the instants from the first day's start to the day after the last; a numberRange's bounds.
|
|
206
|
+
function buildJsonRestRangeFilterValues(filter = {}, value) {
|
|
207
|
+
const bounds = {};
|
|
208
|
+
if (filter.type === CRUD_LIST_FILTER_TYPE_DATE || filter.type === CRUD_LIST_FILTER_TYPE_DATE_RANGE) {
|
|
209
|
+
const { from, to } = filter.type === CRUD_LIST_FILTER_TYPE_DATE ? { from: value, to: value } : value || {};
|
|
210
|
+
const nextDate = to ? addDaysToDateFilterValue(to, 1) : "";
|
|
211
|
+
if (from) {
|
|
212
|
+
bounds[renderInternalJsonRestFilterKey(filter, "from")] = dateFilterDayStart(from);
|
|
258
213
|
}
|
|
259
|
-
if (
|
|
260
|
-
|
|
261
|
-
if (nextDate) {
|
|
262
|
-
target[renderInternalJsonRestFilterKey(filter, "toExclusive")] = dateFilterDayStart(nextDate);
|
|
263
|
-
}
|
|
214
|
+
if (nextDate) {
|
|
215
|
+
bounds[renderInternalJsonRestFilterKey(filter, "toExclusive")] = dateFilterDayStart(nextDate);
|
|
264
216
|
}
|
|
265
|
-
return;
|
|
266
217
|
}
|
|
267
218
|
|
|
268
219
|
if (filter.type === CRUD_LIST_FILTER_TYPE_NUMBER_RANGE) {
|
|
269
220
|
if (value?.min != null) {
|
|
270
|
-
|
|
221
|
+
bounds[renderInternalJsonRestFilterKey(filter, "min")] = value.min;
|
|
271
222
|
}
|
|
272
223
|
if (value?.max != null) {
|
|
273
|
-
|
|
224
|
+
bounds[renderInternalJsonRestFilterKey(filter, "max")] = value.max;
|
|
274
225
|
}
|
|
275
|
-
return;
|
|
276
226
|
}
|
|
277
227
|
|
|
278
|
-
|
|
228
|
+
return bounds;
|
|
279
229
|
}
|
|
280
230
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
231
|
+
/**
|
|
232
|
+
* How one filter reaches json-rest-api: the search schema entries it declares, and the filter values
|
|
233
|
+
* `toJsonRestQuery` sends for its parsed value. Both come from here, so a list sends only keys its search schema
|
|
234
|
+
* declares. A filter with a custom apply sends its own key with its parsed value, whatever its type (a day,
|
|
235
|
+
* `{ from, to }` or `{ min, max }`), which is what `applyQuery` hands that apply; a range filter without one sends its
|
|
236
|
+
* internal bound keys, which compare its field.
|
|
237
|
+
*/
|
|
238
|
+
function resolveJsonRestFilterProjection(filter, { columns, apply }) {
|
|
239
|
+
const ownKey = (schemaEntry) => ({
|
|
240
|
+
filter,
|
|
241
|
+
schema: { [filter.queryKey]: schemaEntry },
|
|
242
|
+
values: (value) => ({ [filter.queryKey]: value })
|
|
243
|
+
});
|
|
244
|
+
// readable-check: allow method-probe - input validation: apply holds an application's optional custom filters; other filters use the default
|
|
245
|
+
const customApply = typeof apply[filter.key] === "function" ? apply[filter.key] : null;
|
|
246
|
+
if (customApply) {
|
|
247
|
+
return ownKey(buildJsonRestCustomFilterSearchSchemaEntry(filter, customApply));
|
|
248
|
+
}
|
|
287
249
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
250
|
+
const actualField = resolveJsonRestFilterActualField(filter, columns);
|
|
251
|
+
const simpleEntry = buildJsonRestSimpleFilterSearchSchemaEntry(filter, { actualField });
|
|
252
|
+
if (simpleEntry) {
|
|
253
|
+
return ownKey(simpleEntry);
|
|
292
254
|
}
|
|
293
255
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
256
|
+
if (filter.type === CRUD_LIST_FILTER_TYPE_PRESENCE) {
|
|
257
|
+
return ownKey(buildJsonRestPresenceFilterSearchSchemaEntry(filter, { actualField }));
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
filter,
|
|
262
|
+
schema: buildJsonRestRangeFilterSearchSchemaEntries(filter, { actualField }),
|
|
263
|
+
values: (value) => buildJsonRestRangeFilterValues(filter, value)
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function resolveJsonRestFilterProjections(runtime = {}, { columns = {}, apply = {} } = {}) {
|
|
268
|
+
const normalizedColumns = normalizeColumnsMap(columns);
|
|
269
|
+
return resolveCrudListFilterEntries(runtime)
|
|
270
|
+
.map((filter) => resolveJsonRestFilterProjection(filter, { columns: normalizedColumns, apply }));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function mergeJsonRestSearchSchema(projections = []) {
|
|
274
|
+
return Object.freeze(Object.assign({}, ...projections.map((projection) => projection.schema)));
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function createCrudListFilterJsonRestSearchSchema(runtime = {}, { columns = {}, apply = {} } = {}) {
|
|
278
|
+
return mergeJsonRestSearchSchema(resolveJsonRestFilterProjections(runtime, { columns, apply }));
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* A filter runtime's search schema and its `toJsonRestQuery(query)`, which keeps the query's other keys and replaces
|
|
283
|
+
* each filter's value with the filter values its projection sends for it.
|
|
284
|
+
* @param {{ filters: Record<string, object>, parseQuery: (query: object) => Record<string, unknown> }} runtime
|
|
285
|
+
*/
|
|
286
|
+
function createCrudListFilterJsonRest(runtime, { columns = {}, apply = {} } = {}) {
|
|
287
|
+
const projections = resolveJsonRestFilterProjections(runtime, { columns, apply });
|
|
288
|
+
const filterQueryKeys = new Set(projections.map(({ filter }) => filter.queryKey));
|
|
289
|
+
|
|
290
|
+
function toJsonRestQuery(query = {}) {
|
|
291
|
+
const source = normalizeObjectInput(query);
|
|
292
|
+
const parsedFilters = runtime.parseQuery(source);
|
|
293
|
+
const normalized = {};
|
|
294
|
+
|
|
295
|
+
for (const [key, value] of Object.entries(source)) {
|
|
296
|
+
if (!filterQueryKeys.has(key)) {
|
|
297
|
+
normalized[key] = value;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
for (const { filter, values } of projections) {
|
|
302
|
+
if (Object.hasOwn(parsedFilters, filter.key)) {
|
|
303
|
+
Object.assign(normalized, values(parsedFilters[filter.key]));
|
|
304
|
+
}
|
|
297
305
|
}
|
|
298
306
|
|
|
299
|
-
|
|
307
|
+
return normalized;
|
|
300
308
|
}
|
|
301
309
|
|
|
302
|
-
return
|
|
310
|
+
return Object.freeze({
|
|
311
|
+
searchSchema: mergeJsonRestSearchSchema(projections),
|
|
312
|
+
toJsonRestQuery
|
|
313
|
+
});
|
|
303
314
|
}
|
|
304
315
|
|
|
305
316
|
export {
|
|
306
317
|
normalizeColumnsMap,
|
|
307
318
|
createCrudListFilterJsonRestSearchSchema,
|
|
308
|
-
|
|
319
|
+
createCrudListFilterJsonRest
|
|
309
320
|
};
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
import {
|
|
10
10
|
normalizeColumnsMap,
|
|
11
11
|
createCrudListFilterJsonRestSearchSchema,
|
|
12
|
-
|
|
12
|
+
createCrudListFilterJsonRest
|
|
13
13
|
} from "./listFilterJsonRest.js";
|
|
14
14
|
import {
|
|
15
15
|
buildCrudListFilterQueryField,
|
|
@@ -101,24 +101,20 @@ function createCrudListFilters(definitions = {}, { columns = {}, apply = {} } =
|
|
|
101
101
|
return queryValidatorsByInvalidValueMode[invalidValueMode];
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
104
|
+
const jsonRest = createCrudListFilterJsonRest({
|
|
105
|
+
filters: normalizedFilters,
|
|
106
|
+
parseQuery: parseFilterPayload
|
|
107
|
+
}, {
|
|
108
|
+
columns: normalizedColumns,
|
|
109
|
+
apply
|
|
110
|
+
});
|
|
110
111
|
|
|
111
112
|
return Object.freeze({
|
|
112
113
|
filters: normalizedFilters,
|
|
113
114
|
createQueryValidator,
|
|
114
115
|
parseQuery: parseFilterPayload,
|
|
115
|
-
toJsonRestQuery,
|
|
116
|
-
jsonRestSearchSchema:
|
|
117
|
-
filters: normalizedFilters
|
|
118
|
-
}, {
|
|
119
|
-
columns: normalizedColumns,
|
|
120
|
-
apply
|
|
121
|
-
}),
|
|
116
|
+
toJsonRestQuery: jsonRest.toJsonRestQuery,
|
|
117
|
+
jsonRestSearchSchema: jsonRest.searchSchema,
|
|
122
118
|
applyQuery
|
|
123
119
|
});
|
|
124
120
|
}
|
|
@@ -116,8 +116,8 @@ function fieldsetKeysRefusal(contract, resourceTypes) {
|
|
|
116
116
|
* its view output names, and each type it links to. A type its includes reach below their first level
|
|
117
117
|
* (`includeFields: ["name", { breed: ["name"] }]` reaches the breed's type) is named only by the tables an include
|
|
118
118
|
* crosses, so this schema cannot name it. Such a key is refused, like any other unknown key, unless
|
|
119
|
-
* `deferIncludedTypes` lets it through to createIncludedFieldsetsCheck, which the CRUD actions run
|
|
120
|
-
* resolved those types.
|
|
119
|
+
* `deferIncludedTypes` lets it through to createIncludedFieldsetsCheck, which the CRUD list and view actions run as
|
|
120
|
+
* their input's checkInput, right after this schema, once boot has resolved those types.
|
|
121
121
|
* @param {object} [options]
|
|
122
122
|
* @param {object} [options.resource] The CRUD contract.
|
|
123
123
|
* @param {boolean} [options.deferIncludedTypes]
|
|
@@ -172,7 +172,8 @@ function createJsonApiFieldsetsQueryValidator({ resource = {}, deferIncludedType
|
|
|
172
172
|
* it there; any other key is refused as the validator refuses one. So
|
|
173
173
|
* `include=customer,customer.region&fields[regions]=name` narrows the included regions when the include lists
|
|
174
174
|
* `{ region: ["name", ...] }`, and the includes still decide what an included record can show. The check throws a
|
|
175
|
-
* validation error naming each refused fieldset
|
|
175
|
+
* validation error naming each refused fieldset, which the action pipeline answers as it answers the schema's refusal
|
|
176
|
+
* of a key (ACTION_VALIDATION_FAILED, before the action runs).
|
|
176
177
|
* @param {object} resource The CRUD contract.
|
|
177
178
|
* @returns {(fields: unknown, includedTypes: ReadonlyMap<string, ReadonlySet<string>>) => void} Takes the validated
|
|
178
179
|
* input's `fields` and the types the includes reach below their first level, each with the fields it shows there,
|
|
@@ -10,6 +10,7 @@ import { returnJsonApiDocument } from "@jskit-ai/http-runtime/shared";
|
|
|
10
10
|
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
11
11
|
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
12
12
|
import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
|
|
13
|
+
import { resolveIncludedTypes } from "../src/server/jsonApiModule/service.js";
|
|
13
14
|
import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
|
|
14
15
|
|
|
15
16
|
const BOOKINGS = Object.freeze([
|
|
@@ -50,7 +51,24 @@ function lookupField(namespace, relationshipName) {
|
|
|
50
51
|
};
|
|
51
52
|
}
|
|
52
53
|
|
|
53
|
-
|
|
54
|
+
// The table the bookings' pet include crosses, which names the pet's breed as the type "breeds".
|
|
55
|
+
const PETS_TABLE = defineTableResource({
|
|
56
|
+
name: "pets",
|
|
57
|
+
tableName: "pets",
|
|
58
|
+
ownership: "public",
|
|
59
|
+
schema: {
|
|
60
|
+
name: { type: "string", required: true },
|
|
61
|
+
species: { type: "string", required: true },
|
|
62
|
+
contactId: lookupField("contacts", "contact"),
|
|
63
|
+
breedId: lookupField("breeds", "breed")
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* @param {object} [options]
|
|
69
|
+
* @param {boolean} [options.nested] The pet include also reaches the pet's breed, a level below it.
|
|
70
|
+
*/
|
|
71
|
+
function createBookingsResource({ nested = false } = {}) {
|
|
54
72
|
const bookings = defineTableResource({
|
|
55
73
|
name: "bookings",
|
|
56
74
|
tableName: "bookings",
|
|
@@ -71,9 +89,12 @@ function createBookingsResource() {
|
|
|
71
89
|
containerKey: "lookups"
|
|
72
90
|
}
|
|
73
91
|
},
|
|
74
|
-
fields:
|
|
75
|
-
|
|
76
|
-
|
|
92
|
+
fields: {
|
|
93
|
+
...Object.fromEntries(
|
|
94
|
+
["serviceId", "productId", "contactId", "petId", "summary"].map((field) => [field, { output: "required" }])
|
|
95
|
+
),
|
|
96
|
+
...(nested ? { petId: { output: { required: true, includeFields: ["name", "species", { breed: ["name"] }] } } } : {})
|
|
97
|
+
}
|
|
77
98
|
});
|
|
78
99
|
}
|
|
79
100
|
|
|
@@ -150,8 +171,12 @@ function createBookingDocument(query = {}) {
|
|
|
150
171
|
};
|
|
151
172
|
}
|
|
152
173
|
|
|
153
|
-
|
|
154
|
-
|
|
174
|
+
/**
|
|
175
|
+
* @param {object} [options]
|
|
176
|
+
* @param {boolean} [options.nested] See createBookingsResource.
|
|
177
|
+
*/
|
|
178
|
+
function createFixture({ nested = false } = {}) {
|
|
179
|
+
const resource = createBookingsResource({ nested });
|
|
155
180
|
const calls = [];
|
|
156
181
|
const service = {
|
|
157
182
|
async list(query, { context }) {
|
|
@@ -182,7 +207,9 @@ function createFixture() {
|
|
|
182
207
|
permissionForOperation: () => ({
|
|
183
208
|
require: "all",
|
|
184
209
|
permissions: ["bookings.list"]
|
|
185
|
-
})
|
|
210
|
+
}),
|
|
211
|
+
// What the CRUD contracts resolve at boot, from the tables the includes cross.
|
|
212
|
+
includedTypes: () => resolveIncludedTypes(resource, (name) => (name === "pets" ? PETS_TABLE : null))
|
|
186
213
|
}));
|
|
187
214
|
const actions = createActionCatalogue();
|
|
188
215
|
actions.register({
|
|
@@ -480,3 +507,49 @@ test("generated CRUD list contracts conform through native assistant discovery a
|
|
|
480
507
|
});
|
|
481
508
|
});
|
|
482
509
|
});
|
|
510
|
+
|
|
511
|
+
test("a generated CRUD list whose include reaches nested types refuses an alias or unknown fieldset key before it runs, naming the field and its type to the assistant", async () => {
|
|
512
|
+
const fixture = createFixture({ nested: true });
|
|
513
|
+
const listDefinition = fixture.definitions.find((entry) => entry.id === "crud.bookings.list");
|
|
514
|
+
// The generated input with another execute, as a test that stubs the action's work registers it: the input alone refuses.
|
|
515
|
+
const executed = [];
|
|
516
|
+
const actions = createActionCatalogue();
|
|
517
|
+
actions.register({
|
|
518
|
+
contributorId: "test.generated-bookings",
|
|
519
|
+
domain: "bookings",
|
|
520
|
+
actions: [{
|
|
521
|
+
...listDefinition,
|
|
522
|
+
execute: (input, context, deps) => {
|
|
523
|
+
executed.push(input);
|
|
524
|
+
return listDefinition.execute(input, context, deps);
|
|
525
|
+
}
|
|
526
|
+
}]
|
|
527
|
+
});
|
|
528
|
+
const catalog = createServiceToolCatalog(actions);
|
|
529
|
+
const toolSet = catalog.resolveToolSet(fixture.context);
|
|
530
|
+
const { name: toolName } = toolSet.tools.find(({ actionId }) => actionId === "crud.bookings.list");
|
|
531
|
+
const list = (input) => catalog.executeToolCall({
|
|
532
|
+
toolName,
|
|
533
|
+
argumentsText: JSON.stringify(input),
|
|
534
|
+
context: fixture.context,
|
|
535
|
+
toolSet
|
|
536
|
+
});
|
|
537
|
+
|
|
538
|
+
for (const [fields, field] of [[{ pet: ["name"] }, "fields.pet"], [{ nosuch: ["name"] }, "fields.nosuch"]]) {
|
|
539
|
+
const response = await list({ include: "pet", fields, limit: 3 });
|
|
540
|
+
assert.equal(response.ok, false);
|
|
541
|
+
assert.equal(response.error.code, "ACTION_VALIDATION_FAILED");
|
|
542
|
+
assert.equal(response.error.status, 400);
|
|
543
|
+
assert.ok(response.error.message.startsWith(
|
|
544
|
+
`Validation failed. ${field}: fields keys must be JSON:API resource types. Allowed keys: "bookings", "services", ` +
|
|
545
|
+
'"products", "contacts", "pets", "breeds". Relationship aliases are invalid keys; use "services" instead of "service";'
|
|
546
|
+
), response.error.message);
|
|
547
|
+
}
|
|
548
|
+
assert.deepEqual(executed, []);
|
|
549
|
+
|
|
550
|
+
// A fieldset for the breed the include reaches below its first level still narrows it.
|
|
551
|
+
const narrowed = await list({ fields: { breeds: ["name"] }, limit: 3 });
|
|
552
|
+
assert.equal(narrowed.ok, true, JSON.stringify(narrowed.error));
|
|
553
|
+
assert.equal(executed.length, 1);
|
|
554
|
+
assert.deepEqual(fixture.calls.at(-1).query.fields, { breeds: ["name"] });
|
|
555
|
+
});
|
|
@@ -19,17 +19,19 @@ const orders = defineTableResource({
|
|
|
19
19
|
reference: { type: "string", required: true },
|
|
20
20
|
arrivedAt: { type: "dateTime", storage: { column: "arrived_at" } },
|
|
21
21
|
total: { type: "number" },
|
|
22
|
-
customerId: { type: "id", nullable: true, storage: { column: "customer_id" } }
|
|
22
|
+
customerId: { type: "id", nullable: true, storage: { column: "customer_id" } },
|
|
23
|
+
// A day held as text ("2026-03-05"), the same on every database, which only a custom apply filters.
|
|
24
|
+
dueOn: { type: "string", nullable: true, storage: { column: "due_on" } }
|
|
23
25
|
}
|
|
24
26
|
});
|
|
25
27
|
|
|
26
28
|
// Each arrives at noon UTC, well inside its day in any time zone.
|
|
27
29
|
const ORDERS = Object.freeze([
|
|
28
|
-
{ reference: "A", arrivedAt: "2026-02-27T12:00:00.000Z", total: 5, customerId: "1" },
|
|
29
|
-
{ reference: "B", arrivedAt: "2026-03-02T12:00:00.000Z", total: 10, customerId: "2" },
|
|
30
|
-
{ reference: "C", arrivedAt: "2026-03-15T12:00:00.000Z", total: 20, customerId: "3" },
|
|
31
|
-
{ reference: "D", arrivedAt: "2026-03-30T12:00:00.000Z", total: 30, customerId: "1" },
|
|
32
|
-
{ reference: "E", arrivedAt: "2026-04-03T12:00:00.000Z", total: 40, customerId: null }
|
|
30
|
+
{ reference: "A", arrivedAt: "2026-02-27T12:00:00.000Z", total: 5, customerId: "1", dueOn: "2026-02-28" },
|
|
31
|
+
{ reference: "B", arrivedAt: "2026-03-02T12:00:00.000Z", total: 10, customerId: "2", dueOn: "2026-03-05" },
|
|
32
|
+
{ reference: "C", arrivedAt: "2026-03-15T12:00:00.000Z", total: 20, customerId: "3", dueOn: "2026-03-20" },
|
|
33
|
+
{ reference: "D", arrivedAt: "2026-03-30T12:00:00.000Z", total: 30, customerId: "1", dueOn: "2026-03-31" },
|
|
34
|
+
{ reference: "E", arrivedAt: "2026-04-03T12:00:00.000Z", total: 40, customerId: null, dueOn: null }
|
|
33
35
|
]);
|
|
34
36
|
|
|
35
37
|
/**
|
|
@@ -38,10 +40,11 @@ const ORDERS = Object.freeze([
|
|
|
38
40
|
* @param {import("node:test").TestContext} t
|
|
39
41
|
* @param {object} definitions The list filters.
|
|
40
42
|
* @param {Record<string, string>} columns Each filter's field, when it is not the filter's own key.
|
|
43
|
+
* @param {Record<string, Function>} [apply] The filters with a custom apply.
|
|
41
44
|
*/
|
|
42
|
-
async function ordersApp(t, definitions, columns) {
|
|
45
|
+
async function ordersApp(t, definitions, columns, apply = {}) {
|
|
43
46
|
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
44
|
-
const filters = createCrudListFilterContract(definitions, { columns });
|
|
47
|
+
const filters = createCrudListFilterContract(definitions, { columns, apply });
|
|
45
48
|
const router = createRouter();
|
|
46
49
|
const started = await startTestFeatures({
|
|
47
50
|
knex,
|
|
@@ -115,6 +118,55 @@ test("a date range or number range list filter sent over HTTP answers exactly th
|
|
|
115
118
|
}
|
|
116
119
|
});
|
|
117
120
|
|
|
121
|
+
test("a date, date range or number range list filter with a custom apply answers its rows over HTTP", async (t) => {
|
|
122
|
+
// A default date filter compares dateTime instants, so the due day, held as text, is compared by custom applies.
|
|
123
|
+
// Each records the value it receives: the filter's parsed value, as applyQuery hands it.
|
|
124
|
+
const received = [];
|
|
125
|
+
const list = await ordersApp(t, {
|
|
126
|
+
due: { type: "dateRange", label: "Due" },
|
|
127
|
+
dueBy: { type: "date", label: "Due by" },
|
|
128
|
+
spend: { type: "numberRange", label: "Spend" }
|
|
129
|
+
}, {}, {
|
|
130
|
+
due(queryBuilder, value) {
|
|
131
|
+
received.push(["due", value]);
|
|
132
|
+
if (value.from) queryBuilder.where("due_on", ">=", value.from);
|
|
133
|
+
if (value.to) queryBuilder.where("due_on", "<=", value.to);
|
|
134
|
+
},
|
|
135
|
+
// Due on or before the day, where a default date filter takes only that day.
|
|
136
|
+
dueBy(queryBuilder, value) {
|
|
137
|
+
received.push(["dueBy", value]);
|
|
138
|
+
queryBuilder.where("due_on", "<=", value);
|
|
139
|
+
},
|
|
140
|
+
spend(queryBuilder, value) {
|
|
141
|
+
received.push(["spend", value]);
|
|
142
|
+
if (value.min != null) queryBuilder.where("total", ">=", value.min);
|
|
143
|
+
if (value.max != null) queryBuilder.where("total", "<=", value.max);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
for (const [query, references, values] of [
|
|
148
|
+
["filter%5Bdue%5D=2026-03-01..2026-03-31", ["B", "C", "D"], [["due", { from: "2026-03-01", to: "2026-03-31" }]]],
|
|
149
|
+
["filter%5Bdue%5D=2026-03-21..", ["D"], [["due", { from: "2026-03-21" }]]],
|
|
150
|
+
["filter%5Bdue%5D=..2026-03-05", ["A", "B"], [["due", { to: "2026-03-05" }]]],
|
|
151
|
+
["filter%5Bdue%5D=2026-03-20", ["C"], [["due", { from: "2026-03-20", to: "2026-03-20" }]]],
|
|
152
|
+
["filter%5BdueBy%5D=2026-03-05", ["A", "B"], [["dueBy", "2026-03-05"]]],
|
|
153
|
+
["filter%5Bspend%5D=15..35", ["C", "D"], [["spend", { min: 15, max: 35 }]]],
|
|
154
|
+
["filter%5BdueBy%5D=2026-03-25&filter%5Bspend%5D=10..", ["B", "C"], [["dueBy", "2026-03-25"], ["spend", { min: 10 }]]]
|
|
155
|
+
]) {
|
|
156
|
+
received.length = 0;
|
|
157
|
+
const response = await list(query);
|
|
158
|
+
// Before, toJsonRestQuery sent such a filter as __jskit_<key>_from/_toExclusive (or _min/_max), keys its search
|
|
159
|
+
// schema did not declare, so json-rest-api refused the list with 422 "Field not allowed".
|
|
160
|
+
assert.equal(response.statusCode, 200, `${query}: ${response.body}`);
|
|
161
|
+
assert.deepEqual(response.references, references, query);
|
|
162
|
+
assert.deepEqual(received, values, query);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
for (const query of ["filter%5Bdue%5D=March", "filter%5BdueBy%5D=2026-03-01..2026-03-05", "filter%5Bspend%5D=lots"]) {
|
|
166
|
+
assert.equal((await list(query)).statusCode, 400, query);
|
|
167
|
+
}
|
|
168
|
+
});
|
|
169
|
+
|
|
118
170
|
test("a recordIdMany list filter builds its search schema and answers the rows of the ids sent over HTTP", async (t) => {
|
|
119
171
|
// Before, json-rest-schema refused the filter's search schema entry, whose items were a JSON Schema anyOf, so the
|
|
120
172
|
// orders feature did not start.
|
package/test/listFilters.test.js
CHANGED
|
@@ -641,6 +641,40 @@ test("createCrudListFilterContract builds route validators and JSON REST search
|
|
|
641
641
|
assert.deepEqual(calls, [["whereNull", "location_id"]]);
|
|
642
642
|
});
|
|
643
643
|
|
|
644
|
+
test("createCrudListFilterContract's toJsonRestQuery sends exactly the keys its search schema declares, with or without a custom apply", () => {
|
|
645
|
+
// One filter of every type, each with a value that sets all its bounds.
|
|
646
|
+
const filters = {
|
|
647
|
+
open: [{ type: "flag", label: "Open" }, "true"],
|
|
648
|
+
status: [{ type: "enum", label: "Status", options: [{ value: "active", label: "Active" }] }, "active"],
|
|
649
|
+
tags: [{ type: "enumMany", label: "Tags", options: [{ value: "a", label: "A" }, { value: "b", label: "B" }] }, "a,b"],
|
|
650
|
+
owner: [{ type: "recordId", label: "Owner" }, "7"],
|
|
651
|
+
suppliers: [{ type: "recordIdMany", label: "Suppliers" }, ["7", "4"]],
|
|
652
|
+
arrivedOn: [{ type: "date", label: "Arrived on" }, "2026-04-01"],
|
|
653
|
+
arrival: [{ type: "dateRange", label: "Arrival" }, "2026-04-01..2026-04-30"],
|
|
654
|
+
weight: [{ type: "numberRange", label: "Weight" }, "12.5..18"],
|
|
655
|
+
storage: [{ type: "presence", label: "Storage" }, "missing"]
|
|
656
|
+
};
|
|
657
|
+
const definitions = Object.fromEntries(Object.entries(filters).map(([key, [definition]]) => [key, definition]));
|
|
658
|
+
const query = Object.fromEntries(Object.entries(filters).map(([key, [, value]]) => [key, value]));
|
|
659
|
+
const everyApply = Object.fromEntries(Object.keys(filters).map((key) => [key, () => {}]));
|
|
660
|
+
|
|
661
|
+
for (const apply of [{}, everyApply]) {
|
|
662
|
+
const contract = createCrudListFilterContract(definitions, { apply });
|
|
663
|
+
const sent = contract.toJsonRestQuery(query);
|
|
664
|
+
// Before, a date, dateRange or numberRange filter with a custom apply declared only its own key but sent
|
|
665
|
+
// __jskit_<key>_from/_toExclusive (or _min/_max), which json-rest-api refused as "Field not allowed".
|
|
666
|
+
assert.deepEqual(Object.keys(sent).sort(), Object.keys(contract.jsonRestSearchSchema).sort());
|
|
667
|
+
assert.deepEqual(createSchema(contract.jsonRestSearchSchema).patch(sent).errors, {});
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
// A filter with a custom apply sends its own key with its parsed value, the value applyQuery hands that apply.
|
|
671
|
+
const custom = createCrudListFilterContract(definitions, { apply: everyApply });
|
|
672
|
+
assert.deepEqual(custom.toJsonRestQuery(query), { ...custom.parseQuery(query) });
|
|
673
|
+
assert.deepEqual(custom.toJsonRestQuery(query).arrival, { from: "2026-04-01", to: "2026-04-30" });
|
|
674
|
+
assert.deepEqual(custom.toJsonRestQuery(query).weight, { min: 12.5, max: 18 });
|
|
675
|
+
assert.equal(custom.toJsonRestQuery(query).arrivedOn, "2026-04-01");
|
|
676
|
+
});
|
|
677
|
+
|
|
644
678
|
test("createCrudListFilterContract defaults route validation to reject invalid values", () => {
|
|
645
679
|
const contract = createCrudListFilterContract({
|
|
646
680
|
status: {
|
|
@@ -62,8 +62,27 @@ const ordersContract = defineCrudContract(orders, {
|
|
|
62
62
|
customerId: { output: { required: false, includeFields: ["name", { region: ["name", "code"] }] } }
|
|
63
63
|
}
|
|
64
64
|
});
|
|
65
|
+
// invoices -> customer (customers), one level: nothing to defer, so the list's input schema judges every fieldset key.
|
|
66
|
+
const invoices = defineTableResource({
|
|
67
|
+
name: "invoices",
|
|
68
|
+
tableName: "invoices",
|
|
69
|
+
ownership: "public",
|
|
70
|
+
schema: {
|
|
71
|
+
number: { type: "string", required: true },
|
|
72
|
+
customerId: { type: "id", nullable: true, lookup: "customers", storage: { column: "customer_id" } }
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
const invoicesContract = defineCrudContract(invoices, {
|
|
76
|
+
namespace: "invoices",
|
|
77
|
+
apiAccess: "public",
|
|
78
|
+
operations: ["list", "view"],
|
|
79
|
+
fields: {
|
|
80
|
+
number: { output: "required" },
|
|
81
|
+
customerId: { output: { required: false, includeFields: ["name"] } }
|
|
82
|
+
}
|
|
83
|
+
});
|
|
65
84
|
|
|
66
|
-
// The orders
|
|
85
|
+
// The orders and invoices features serve their records; another feature owns the tables their includes reach.
|
|
67
86
|
async function startOrders(t) {
|
|
68
87
|
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
69
88
|
const router = createRouter();
|
|
@@ -72,7 +91,8 @@ async function startOrders(t) {
|
|
|
72
91
|
features: [
|
|
73
92
|
CrudContractsProvider,
|
|
74
93
|
defineFeature({ id: "test.customers", owns: [customers, regions, tags], setup: () => ({}) }),
|
|
75
|
-
defineCrudFeature({ crud: ordersContract, surface: "home" })
|
|
94
|
+
defineCrudFeature({ crud: ordersContract, surface: "home" }),
|
|
95
|
+
defineCrudFeature({ crud: invoicesContract, surface: "home" })
|
|
76
96
|
],
|
|
77
97
|
requires: { actions: "runtime.actions" },
|
|
78
98
|
inputs: { "runtime.http": { router } },
|
|
@@ -83,6 +103,7 @@ async function startOrders(t) {
|
|
|
83
103
|
await knex("customers").insert({ name: "Acme", region_id: 1 });
|
|
84
104
|
await knex("tags").insert({ label: "Urgent" });
|
|
85
105
|
await knex("orders").insert({ reference: "A-1", customer_id: 1 });
|
|
106
|
+
await knex("invoices").insert({ number: "INV-1", customer_id: 1 });
|
|
86
107
|
return { actions: started.capabilities.actions, router };
|
|
87
108
|
}
|
|
88
109
|
|
|
@@ -155,3 +176,63 @@ test("over HTTP, fields[<type>] narrows a record two include levels down and ref
|
|
|
155
176
|
assert.ok(response.body.includes(`"${code}"`), `${query}: ${response.body}`);
|
|
156
177
|
}
|
|
157
178
|
});
|
|
179
|
+
|
|
180
|
+
// The list action's input schema refuses a bad key of a contract whose includes stop at their first level; the check
|
|
181
|
+
// the action runs refuses it for one whose includes reach further. A client or an assistant tool reads both alike.
|
|
182
|
+
const BAD_KEYS = Object.freeze([
|
|
183
|
+
[{ customer: ["name"] }, "fields.customer"],
|
|
184
|
+
[{ nosuch: ["name"] }, "fields.nosuch"]
|
|
185
|
+
]);
|
|
186
|
+
|
|
187
|
+
test("a fieldset keyed by a relationship alias or by no type is refused as the action input refuses one, whether the includes reach nested types or not", async (t) => {
|
|
188
|
+
const { actions } = await startOrders(t);
|
|
189
|
+
const refusal = (actionId, fields) => actions.execute({ actionId, input: { include: "customer", fields }, context: API }).then(
|
|
190
|
+
() => assert.fail(`${actionId} took fields ${JSON.stringify(fields)}`),
|
|
191
|
+
(error) => error
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
for (const [fields, field] of BAD_KEYS) {
|
|
195
|
+
const nested = await refusal("crud.orders.list", fields);
|
|
196
|
+
const flat = await refusal("crud.invoices.list", fields);
|
|
197
|
+
assert.equal(nested.constructor, flat.constructor);
|
|
198
|
+
for (const [error, allowedKeys] of [[nested, '"orders", "customers", "regions"'], [flat, '"invoices", "customers"']]) {
|
|
199
|
+
assert.equal(error.status, 400);
|
|
200
|
+
assert.equal(error.code, "ACTION_VALIDATION_FAILED");
|
|
201
|
+
assert.equal(error.message, "Validation failed.");
|
|
202
|
+
assert.deepEqual(Object.keys(error.details.fieldErrors), [field]);
|
|
203
|
+
assert.deepEqual(error.details.fieldErrorCodes[field], {
|
|
204
|
+
code: "crud.query.fieldsKeysInvalidWithAliases",
|
|
205
|
+
params: { allowedTypes: allowedKeys, aliasGuidance: 'use "customers" instead of "customer"' }
|
|
206
|
+
});
|
|
207
|
+
assert.equal(
|
|
208
|
+
error.details.fieldErrors[field],
|
|
209
|
+
`fields keys must be JSON:API resource types. Allowed keys: ${allowedKeys}. Relationship aliases are invalid ` +
|
|
210
|
+
'keys; use "customers" instead of "customer".'
|
|
211
|
+
);
|
|
212
|
+
assertCatalogRenders(error.details.fieldErrorCodes[field], error.details.fieldErrors[field]);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
test("over HTTP, a fieldset keyed by a relationship alias or by no type answers alike whether the includes reach nested types or not", async (t) => {
|
|
218
|
+
const { actions, router } = await startOrders(t);
|
|
219
|
+
const app = Fastify();
|
|
220
|
+
t.after(() => app.close());
|
|
221
|
+
registerApiErrorHandler(app);
|
|
222
|
+
registerRoutes(app, { routes: router.list(), actions });
|
|
223
|
+
const listPath = (namespace) => router.list().find((route) => route.method === "GET" && route.path.endsWith(`/${namespace}`)).path;
|
|
224
|
+
|
|
225
|
+
for (const [fields, field] of BAD_KEYS) {
|
|
226
|
+
const [type] = Object.keys(fields);
|
|
227
|
+
const [nested, flat] = await Promise.all(["orders", "invoices"].map((namespace) => app.inject({
|
|
228
|
+
method: "GET",
|
|
229
|
+
url: `${listPath(namespace)}?include=customer&fields%5B${type}%5D=name`
|
|
230
|
+
})));
|
|
231
|
+
for (const response of [nested, flat]) {
|
|
232
|
+
assert.equal(response.statusCode, 400, `${field}: ${response.body}`);
|
|
233
|
+
for (const expected of ['"ACTION_VALIDATION_FAILED"', '"crud.query.fieldsKeysInvalidWithAliases"', 'use \\"customers\\" instead of \\"customer\\"']) {
|
|
234
|
+
assert.ok(response.body.includes(expected), `${field} ${expected}: ${response.body}`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
});
|