@jskit-ai/crud-core 0.2.25 → 0.2.27
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 +6 -0
- package/locales/en.json +1 -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/crudContracts.js +18 -4
- package/src/server/defineCrudFeature.js +3 -2
- package/src/server/jsonApiModule/actions.js +16 -2
- package/src/server/jsonApiModule/service.js +15 -3
- package/src/server/listFilterJsonRest.js +93 -77
- package/src/server/listFilterTypes.js +18 -17
- package/src/server/listFilters.js +10 -14
- package/src/server/listQueryValidators.js +94 -15
- package/test/assistantActionConformance.test.js +80 -7
- package/test/listFilterRoutes.test.js +190 -0
- package/test/listFilters.test.js +53 -2
- package/test/listQueryValidators.test.js +63 -0
- package/test/listUndeclaredQuery.test.js +2 -2
- package/test/nestedIncludeFieldsets.test.js +238 -0
|
@@ -2,7 +2,9 @@ import { createSchema } from "json-rest-schema";
|
|
|
2
2
|
import {
|
|
3
3
|
cursorPaginationQueryValidator
|
|
4
4
|
} from "@jskit-ai/kernel/shared/validators";
|
|
5
|
-
import {
|
|
5
|
+
import { createValidationError } from "@jskit-ai/kernel/server/runtime/errors";
|
|
6
|
+
import { normalizeJsonApiFieldList } from "@jskit-ai/kernel/shared/support/jsonApiFieldsets";
|
|
7
|
+
import { isRecord, normalizeText } from "@jskit-ai/kernel/shared/support/normalize";
|
|
6
8
|
import { resolveCrudParentFilterKeys } from "@jskit-ai/resource-crud-core/shared/crudLookup";
|
|
7
9
|
import {
|
|
8
10
|
CRUD_LIST_FILTER_TYPE_RECORD_ID_MANY,
|
|
@@ -84,22 +86,18 @@ const jsonApiFieldsetsQueryValidator = Object.freeze({
|
|
|
84
86
|
mode: "patch"
|
|
85
87
|
});
|
|
86
88
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
const
|
|
95
|
-
? `{"${contract.primaryType}":["${firstRelationship.attributeKey}"],` +
|
|
96
|
-
`"${firstRelationship.relationshipType}":["${firstRelationship.labelKey || "id"}"]}`
|
|
97
|
-
: `{"${contract.primaryType}":["id"]}`;
|
|
98
|
-
const allowedTypes = contract.resourceTypes.map((entry) => `"${entry}"`).join(", ");
|
|
89
|
+
/**
|
|
90
|
+
* The coded refusal of a fieldset key that is none of the resource types a read takes, naming the resource type to
|
|
91
|
+
* use for each of the contract's relationship aliases.
|
|
92
|
+
* @param {ReturnType<typeof resolveJsonApiFieldsetContract>} contract
|
|
93
|
+
* @param {readonly string[]} resourceTypes
|
|
94
|
+
*/
|
|
95
|
+
function fieldsetKeysRefusal(contract, resourceTypes) {
|
|
96
|
+
const allowedTypes = resourceTypes.map((entry) => `"${entry}"`).join(", ");
|
|
99
97
|
const aliasGuidance = contract.aliasMappings
|
|
100
98
|
.map((entry) => `use "${entry.resourceType}" instead of "${entry.alias}"`)
|
|
101
99
|
.join("; ");
|
|
102
|
-
|
|
100
|
+
return aliasGuidance
|
|
103
101
|
? {
|
|
104
102
|
code: "crud.query.fieldsKeysInvalidWithAliases",
|
|
105
103
|
message: `fields keys must be JSON:API resource types. Allowed keys: ${allowedTypes}.` +
|
|
@@ -111,6 +109,30 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
111
109
|
message: `fields keys must be JSON:API resource types. Allowed keys: ${allowedTypes}.`,
|
|
112
110
|
params: { allowedTypes }
|
|
113
111
|
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The sparse fieldsets a CRUD contract's reads take, keyed by JSON:API resource type: its own type, with the fields
|
|
116
|
+
* its view output names, and each type it links to. A type its includes reach below their first level
|
|
117
|
+
* (`includeFields: ["name", { breed: ["name"] }]` reaches the breed's type) is named only by the tables an include
|
|
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 list and view actions run as
|
|
120
|
+
* their input's checkInput, right after this schema, once boot has resolved those types.
|
|
121
|
+
* @param {object} [options]
|
|
122
|
+
* @param {object} [options.resource] The CRUD contract.
|
|
123
|
+
* @param {boolean} [options.deferIncludedTypes]
|
|
124
|
+
*/
|
|
125
|
+
function createJsonApiFieldsetsQueryValidator({ resource = {}, deferIncludedTypes = false } = {}) {
|
|
126
|
+
const contract = resolveJsonApiFieldsetContract(resource);
|
|
127
|
+
if (!contract.primaryType || contract.resourceTypes.length < 1) {
|
|
128
|
+
return jsonApiFieldsetsQueryValidator;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const firstRelationship = contract.relationshipEntries[0] || null;
|
|
132
|
+
const example = firstRelationship
|
|
133
|
+
? `{"${contract.primaryType}":["${firstRelationship.attributeKey}"],` +
|
|
134
|
+
`"${firstRelationship.relationshipType}":["${firstRelationship.labelKey || "id"}"]}`
|
|
135
|
+
: `{"${contract.primaryType}":["id"]}`;
|
|
114
136
|
const fieldsetSchema = createSchema(
|
|
115
137
|
Object.fromEntries(
|
|
116
138
|
contract.resourceTypes.map((resourceType) => [
|
|
@@ -121,6 +143,7 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
121
143
|
])
|
|
122
144
|
)
|
|
123
145
|
);
|
|
146
|
+
const reachesNestedTypes = contract.relationshipEntries.some(({ include }) => Object.keys(include.relationships).length > 0);
|
|
124
147
|
|
|
125
148
|
return Object.freeze({
|
|
126
149
|
schema: createSchema({
|
|
@@ -128,13 +151,14 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
128
151
|
type: "object",
|
|
129
152
|
required: false,
|
|
130
153
|
schema: fieldsetSchema,
|
|
154
|
+
...(deferIncludedTypes && reachesNestedTypes ? { additionalProperties: true } : {}),
|
|
131
155
|
messages: {
|
|
132
156
|
default: {
|
|
133
157
|
code: "crud.query.fieldsByTypeInvalid",
|
|
134
158
|
message: `fields expects an object keyed by JSON:API resource type, such as ${example}.`,
|
|
135
159
|
params: { example }
|
|
136
160
|
},
|
|
137
|
-
additionalProperties:
|
|
161
|
+
additionalProperties: fieldsetKeysRefusal(contract, contract.resourceTypes)
|
|
138
162
|
}
|
|
139
163
|
}
|
|
140
164
|
}),
|
|
@@ -142,6 +166,60 @@ function createJsonApiFieldsetsQueryValidator({ resource = {} } = {}) {
|
|
|
142
166
|
});
|
|
143
167
|
}
|
|
144
168
|
|
|
169
|
+
/**
|
|
170
|
+
* The check of the sparse fieldsets createJsonApiFieldsetsQueryValidator deferred: keys for none of the resource types
|
|
171
|
+
* its schema names. A type the resource's includes reach below their first level takes only the fields they show of
|
|
172
|
+
* it there; any other key is refused as the validator refuses one. So
|
|
173
|
+
* `include=customer,customer.region&fields[regions]=name` narrows the included regions when the include lists
|
|
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, which the action pipeline answers as it answers the schema's refusal
|
|
176
|
+
* of a key (ACTION_VALIDATION_FAILED, before the action runs).
|
|
177
|
+
* @param {object} resource The CRUD contract.
|
|
178
|
+
* @returns {(fields: unknown, includedTypes: ReadonlyMap<string, ReadonlySet<string>>) => void} Takes the validated
|
|
179
|
+
* input's `fields` and the types the includes reach below their first level, each with the fields it shows there,
|
|
180
|
+
* as the CRUD contracts resolved them at boot (`includedTypes`).
|
|
181
|
+
*/
|
|
182
|
+
function createIncludedFieldsetsCheck(resource) {
|
|
183
|
+
// Worked out at the first read that names fieldsets, so composing a feature costs nothing more.
|
|
184
|
+
let contract = null;
|
|
185
|
+
let namedTypes = null;
|
|
186
|
+
|
|
187
|
+
return function checkIncludedFieldsets(fields, includedTypes) {
|
|
188
|
+
if (!isRecord(fields)) {
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
contract ??= resolveJsonApiFieldsetContract(resource);
|
|
192
|
+
namedTypes ??= new Set(contract.resourceTypes);
|
|
193
|
+
if (namedTypes.size < 1 || !contract.primaryType) {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const fieldErrors = {};
|
|
197
|
+
for (const [type, value] of Object.entries(fields)) {
|
|
198
|
+
if (namedTypes.has(type)) {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const shown = includedTypes.get(type);
|
|
202
|
+
if (!shown) {
|
|
203
|
+
fieldErrors[`fields.${type}`] = fieldsetKeysRefusal(contract, [...new Set([...namedTypes, ...includedTypes.keys()])]);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const unshown = normalizeJsonApiFieldList(value).filter((name) => !shown.has(name));
|
|
207
|
+
if (unshown.length > 0) {
|
|
208
|
+
const params = { type, shown: [...shown].join(", ") || "none", fields: unshown.join(", ") };
|
|
209
|
+
fieldErrors[`fields.${type}`] = {
|
|
210
|
+
code: "crud.query.fieldsNotShown",
|
|
211
|
+
message: `fields[${params.type}] may name only what this read's includes show of ${params.type}: ` +
|
|
212
|
+
`${params.shown}. It names ${params.fields}.`,
|
|
213
|
+
params
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (Object.keys(fieldErrors).length > 0) {
|
|
218
|
+
throw createValidationError(fieldErrors);
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
145
223
|
function resolveCrudListUsesOrderedCursor(list = {}) {
|
|
146
224
|
const entries = Array.isArray(list.orderBy)
|
|
147
225
|
? list.orderBy
|
|
@@ -250,6 +328,7 @@ function createStandardCrudViewQueryValidators({
|
|
|
250
328
|
|
|
251
329
|
export {
|
|
252
330
|
createCrudCursorPaginationQueryValidator,
|
|
331
|
+
createIncludedFieldsetsCheck,
|
|
253
332
|
createJsonApiFieldsetsQueryValidator,
|
|
254
333
|
listSearchQueryValidator,
|
|
255
334
|
listRecordIdsQueryValidator,
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import Fastify from "fastify";
|
|
4
|
+
import { createPackageTestKnex, startTestFeatures } from "@jskit-ai/resource-runtime/test";
|
|
5
|
+
import { defineTableResource } from "@jskit-ai/resource-core/shared/tableResource";
|
|
6
|
+
import { defineCrudContract } from "@jskit-ai/resource-crud-core/shared/crudContract";
|
|
7
|
+
import { createRouter } from "../../kernel/server/http/lib/router.js";
|
|
8
|
+
import { registerRoutes } from "../../kernel/server/http/lib/routeRegistration.js";
|
|
9
|
+
import { registerApiErrorHandler } from "../../kernel/server/http/errorHandling.js";
|
|
10
|
+
import { CrudContractsProvider } from "../src/server/crudContracts.js";
|
|
11
|
+
import { defineCrudFeature } from "../src/server/defineCrudFeature.js";
|
|
12
|
+
import { createCrudListFilterContract } from "../src/server/listFilters.js";
|
|
13
|
+
|
|
14
|
+
const orders = defineTableResource({
|
|
15
|
+
name: "orders",
|
|
16
|
+
tableName: "orders",
|
|
17
|
+
ownership: "public",
|
|
18
|
+
schema: {
|
|
19
|
+
reference: { type: "string", required: true },
|
|
20
|
+
arrivedAt: { type: "dateTime", storage: { column: "arrived_at" } },
|
|
21
|
+
total: { type: "number" },
|
|
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" } }
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
// Each arrives at noon UTC, well inside its day in any time zone.
|
|
29
|
+
const ORDERS = Object.freeze([
|
|
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 }
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* An orders list served as an application serves one with structured filters: the filter contract's validator at the
|
|
39
|
+
* route and action, its search schema on the orders table, and its toJsonRestQuery in the service's list, over Fastify.
|
|
40
|
+
* @param {import("node:test").TestContext} t
|
|
41
|
+
* @param {object} definitions The list filters.
|
|
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.
|
|
44
|
+
*/
|
|
45
|
+
async function ordersApp(t, definitions, columns, apply = {}) {
|
|
46
|
+
const knex = await createPackageTestKnex(t, { environment: process.env });
|
|
47
|
+
const filters = createCrudListFilterContract(definitions, { columns, apply });
|
|
48
|
+
const router = createRouter();
|
|
49
|
+
const started = await startTestFeatures({
|
|
50
|
+
knex,
|
|
51
|
+
features: [
|
|
52
|
+
CrudContractsProvider,
|
|
53
|
+
defineCrudFeature({
|
|
54
|
+
crud: defineCrudContract(orders, {
|
|
55
|
+
namespace: "orders",
|
|
56
|
+
apiAccess: "public",
|
|
57
|
+
operations: ["list", "view"],
|
|
58
|
+
fields: { reference: { output: "required" } }
|
|
59
|
+
}),
|
|
60
|
+
operations: ["list"],
|
|
61
|
+
surface: "app",
|
|
62
|
+
owns: [{ resource: orders, searchSchema: filters.jsonRestSearchSchema }],
|
|
63
|
+
listFilterQueryValidator: filters.queryValidator,
|
|
64
|
+
decorateService: ({ service }) => ({ ...service, list: (query, options) => service.list(filters.toJsonRestQuery(query), options) })
|
|
65
|
+
})
|
|
66
|
+
],
|
|
67
|
+
requires: { actions: "runtime.actions", orders: "crud.orders" },
|
|
68
|
+
inputs: { "runtime.http": { router } },
|
|
69
|
+
createTables: true
|
|
70
|
+
});
|
|
71
|
+
t.after(started.stop);
|
|
72
|
+
const context = started.resources.declareSystemScope("test.orders", "The test seeds every order.")("seed the orders");
|
|
73
|
+
for (const order of ORDERS) {
|
|
74
|
+
await started.capabilities.orders.repository.create(order, { context, returning: "none" });
|
|
75
|
+
}
|
|
76
|
+
const app = Fastify();
|
|
77
|
+
t.after(() => app.close());
|
|
78
|
+
registerApiErrorHandler(app);
|
|
79
|
+
registerRoutes(app, { routes: router.list(), actions: started.capabilities.actions });
|
|
80
|
+
return async function list(query) {
|
|
81
|
+
const response = await app.inject({ method: "GET", url: `/api/orders?${query}` });
|
|
82
|
+
return {
|
|
83
|
+
statusCode: response.statusCode,
|
|
84
|
+
body: response.body,
|
|
85
|
+
references: response.statusCode === 200 ? response.json().data.map((record) => record.attributes.reference).sort() : null
|
|
86
|
+
};
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
test("a date range or number range list filter sent over HTTP answers exactly the rows inside it", async (t) => {
|
|
91
|
+
// arrival and arrivedOn are mapped to the arrivedAt field; total filters its own field.
|
|
92
|
+
const list = await ordersApp(t, {
|
|
93
|
+
arrival: { type: "dateRange", label: "Arrival" },
|
|
94
|
+
arrivedOn: { type: "date", label: "Arrived on" },
|
|
95
|
+
total: { type: "numberRange", label: "Total" }
|
|
96
|
+
}, { arrival: "arrivedAt", arrivedOn: "arrivedAt" });
|
|
97
|
+
|
|
98
|
+
for (const [query, references] of [
|
|
99
|
+
["filter%5Barrival%5D=2026-03-01..2026-03-31", ["B", "C", "D"]],
|
|
100
|
+
["filter%5Barrival%5D=2026-03-10..", ["C", "D", "E"]],
|
|
101
|
+
["filter%5Barrival%5D=..2026-03-10", ["A", "B"]],
|
|
102
|
+
["filter%5Barrival%5D=2026-03-15", ["C"]],
|
|
103
|
+
["filter%5BarrivedOn%5D=2026-03-30", ["D"]],
|
|
104
|
+
["filter%5Btotal%5D=15..35", ["C", "D"]],
|
|
105
|
+
["filter%5Btotal%5D=..10", ["A", "B"]],
|
|
106
|
+
["filter%5Barrival%5D=2026-03-01..2026-03-31&filter%5Btotal%5D=15..", ["C", "D"]],
|
|
107
|
+
["page%5Blimit%5D=20", ["A", "B", "C", "D", "E"]]
|
|
108
|
+
]) {
|
|
109
|
+
const response = await list(query);
|
|
110
|
+
// Before, a range answered 400: the list action read the route's parsed { from, to } again and refused it. Past
|
|
111
|
+
// that, the service's toJsonRestQuery dropped it, and a date bound "2026-03-01 00:00:00" was refused with 422.
|
|
112
|
+
assert.equal(response.statusCode, 200, `${query}: ${response.body}`);
|
|
113
|
+
assert.deepEqual(response.references, references, query);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
for (const query of ["filter%5Barrival%5D=March", "filter%5Barrival%5D=2026-03-01..soon", "filter%5Btotal%5D=lots", "filter%5Btotal%5D=1..x"]) {
|
|
117
|
+
assert.equal((await list(query)).statusCode, 400, query);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
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
|
+
|
|
170
|
+
test("a recordIdMany list filter builds its search schema and answers the rows of the ids sent over HTTP", async (t) => {
|
|
171
|
+
// Before, json-rest-schema refused the filter's search schema entry, whose items were a JSON Schema anyOf, so the
|
|
172
|
+
// orders feature did not start.
|
|
173
|
+
const list = await ordersApp(t, { customer: { type: "recordIdMany", label: "Customer" } }, { customer: "customerId" });
|
|
174
|
+
|
|
175
|
+
for (const [query, references] of [
|
|
176
|
+
["filter%5Bcustomer%5D=1&filter%5Bcustomer%5D=2", ["A", "B", "D"]],
|
|
177
|
+
["filter%5Bcustomer%5D=1,2", ["A", "B", "D"]],
|
|
178
|
+
["filter%5Bcustomer%5D=1&filter%5Bcustomer%5D=3", ["A", "C", "D"]],
|
|
179
|
+
["filter%5Bcustomer%5D=3", ["C"]],
|
|
180
|
+
["filter%5Bcustomer%5D=9", []]
|
|
181
|
+
]) {
|
|
182
|
+
const response = await list(query);
|
|
183
|
+
assert.equal(response.statusCode, 200, `${query}: ${response.body}`);
|
|
184
|
+
assert.deepEqual(response.references, references, query);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
for (const query of ["filter%5Bcustomer%5D=abc", "filter%5Bcustomer%5D=1,,2", "filter%5Bcustomer%5D=0"]) {
|
|
188
|
+
assert.equal((await list(query)).statusCode, 400, query);
|
|
189
|
+
}
|
|
190
|
+
});
|
package/test/listFilters.test.js
CHANGED
|
@@ -415,6 +415,12 @@ test("createCrudListFilters reject validator keeps strict filter schemas", () =>
|
|
|
415
415
|
);
|
|
416
416
|
assert.deepEqual(transportSchema.properties.status.anyOf[1].items.enum, ["active", "archived"]);
|
|
417
417
|
assert.equal(transportSchema.properties.supplierContactId.anyOf[1].items.anyOf[0].pattern, "^[1-9][0-9]*$");
|
|
418
|
+
// Or one comma-separated value, the form JSON:API gives a list, of valid values only.
|
|
419
|
+
const commaList = (property) => new RegExp(transportSchema.properties[property].anyOf[2].pattern, "u");
|
|
420
|
+
assert.equal(commaList("status").test("active,archived"), true);
|
|
421
|
+
assert.equal(commaList("status").test("active,unexpected"), false);
|
|
422
|
+
assert.equal(commaList("supplierContactId").test("7,4"), true);
|
|
423
|
+
assert.equal(commaList("supplierContactId").test("7,,4"), false);
|
|
418
424
|
assert.equal(
|
|
419
425
|
transportSchema.properties.weight.anyOf[0].pattern,
|
|
420
426
|
"^(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?(?:\\.\\.(?:[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)?)?|\\.\\.[+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)$"
|
|
@@ -596,6 +602,10 @@ test("createCrudListFilterContract builds route validators and JSON REST search
|
|
|
596
602
|
assert.equal(contract.jsonRestSearchSchema.status.filterOperator, "in");
|
|
597
603
|
assert.equal(contract.jsonRestSearchSchema.status.actualField, "status");
|
|
598
604
|
assert.equal(contract.jsonRestSearchSchema.supplierContactId.filterOperator, "in");
|
|
605
|
+
// json-rest-api validates a search value with json-rest-schema, which takes an item's field definition, not JSON Schema.
|
|
606
|
+
assert.deepEqual(contract.jsonRestSearchSchema.supplierContactId.items, { type: "id" });
|
|
607
|
+
assert.deepEqual(createSchema({ supplierContactId: contract.jsonRestSearchSchema.supplierContactId })
|
|
608
|
+
.patch({ supplierContactId: ["7", "4"] }), { validatedObject: { supplierContactId: [7, 4] }, errors: {} });
|
|
599
609
|
assert.equal(contract.jsonRestSearchSchema.__jskit_arrivalDate_from.filterOperator, ">=");
|
|
600
610
|
assert.equal(contract.jsonRestSearchSchema.__jskit_arrivalDate_toExclusive.filterOperator, "<");
|
|
601
611
|
assert.equal(contract.jsonRestSearchSchema.__jskit_weight_min.filterOperator, ">=");
|
|
@@ -614,8 +624,15 @@ test("createCrudListFilterContract builds route validators and JSON REST search
|
|
|
614
624
|
status: ["active", "archived"],
|
|
615
625
|
supplierContactId: ["7", "4"],
|
|
616
626
|
locationAssignment: "missing",
|
|
617
|
-
__jskit_arrivalDate_from: "2026-04-
|
|
618
|
-
__jskit_arrivalDate_toExclusive: "2026-05-
|
|
627
|
+
__jskit_arrivalDate_from: "2026-04-01T00:00:00.000Z",
|
|
628
|
+
__jskit_arrivalDate_toExclusive: "2026-05-01T00:00:00.000Z",
|
|
629
|
+
__jskit_weight_min: 12.5
|
|
630
|
+
});
|
|
631
|
+
// Over HTTP the service's list receives the query the route and the list action already parsed: it maps the same.
|
|
632
|
+
const { validatedObject: parsedQuery } = contract.queryValidator.schema.patch({ arrivalDate: "2026-04-01..2026-04-30", weight: "12.5.." });
|
|
633
|
+
assert.deepEqual(contract.toJsonRestQuery(contract.queryValidator.schema.patch(parsedQuery).validatedObject), {
|
|
634
|
+
__jskit_arrivalDate_from: "2026-04-01T00:00:00.000Z",
|
|
635
|
+
__jskit_arrivalDate_toExclusive: "2026-05-01T00:00:00.000Z",
|
|
619
636
|
__jskit_weight_min: 12.5
|
|
620
637
|
});
|
|
621
638
|
|
|
@@ -624,6 +641,40 @@ test("createCrudListFilterContract builds route validators and JSON REST search
|
|
|
624
641
|
assert.deepEqual(calls, [["whereNull", "location_id"]]);
|
|
625
642
|
});
|
|
626
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
|
+
|
|
627
678
|
test("createCrudListFilterContract defaults route validation to reject invalid values", () => {
|
|
628
679
|
const contract = createCrudListFilterContract({
|
|
629
680
|
status: {
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
lookupIncludeQueryValidator,
|
|
13
13
|
createCrudCursorPaginationQueryValidator,
|
|
14
14
|
createJsonApiFieldsetsQueryValidator,
|
|
15
|
+
createIncludedFieldsetsCheck,
|
|
15
16
|
createCrudParentFilterQueryValidator,
|
|
16
17
|
createStandardCrudListQueryValidators,
|
|
17
18
|
createStandardCrudViewQueryValidators
|
|
@@ -160,6 +161,68 @@ test("resource-aware sparse fieldsets enumerate JSON:API types and reject relati
|
|
|
160
161
|
);
|
|
161
162
|
});
|
|
162
163
|
|
|
164
|
+
test("a fieldset for a type the includes reach below their first level waits for the types boot resolves, then names only fields shown there", () => {
|
|
165
|
+
// orders -> customer (customers) -> region (regions): only the customers table names the region's type.
|
|
166
|
+
const resource = createCrudResource({
|
|
167
|
+
namespace: "orders",
|
|
168
|
+
viewFields: {
|
|
169
|
+
reference: { type: "string" },
|
|
170
|
+
customerId: { type: "integer", belongsTo: "customers", as: "customer", includeFields: ["name", { region: ["name", "code"] }] }
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
const refusal = (run) => {
|
|
174
|
+
try {
|
|
175
|
+
run();
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return error;
|
|
178
|
+
}
|
|
179
|
+
return assert.fail("expected a refusal");
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
// Without deferIncludedTypes the schema refuses the key, as it refuses any type it does not name.
|
|
183
|
+
const strict = refusal(() => validateSchemaPayload(createJsonApiFieldsetsQueryValidator({ resource }), {
|
|
184
|
+
fields: { regions: ["name"] }
|
|
185
|
+
}, { phase: "input" }));
|
|
186
|
+
assert.equal(strict.fieldErrorCodes?.["fields.regions"]?.code, "crud.query.fieldsKeysInvalidWithAliases");
|
|
187
|
+
|
|
188
|
+
// Deferred, the schema lets the keys it cannot name through, and still checks those it names.
|
|
189
|
+
const deferred = createJsonApiFieldsetsQueryValidator({ resource, deferIncludedTypes: true });
|
|
190
|
+
assert.deepEqual(validateSchemaPayload(deferred, {
|
|
191
|
+
fields: { orders: ["reference"], regions: ["name"], tags: ["label"] }
|
|
192
|
+
}, { phase: "input" }), { fields: { orders: ["reference"], regions: ["name"], tags: ["label"] } });
|
|
193
|
+
assert.ok(refusal(() => validateSchemaPayload(deferred, { fields: { orders: ["secret"] } }, { phase: "input" })).fieldErrors);
|
|
194
|
+
// A contract whose includes stop at their first level has nothing to defer.
|
|
195
|
+
const flat = createCrudResource({ namespace: "orders", viewFields: { customerId: { type: "integer", belongsTo: "customers", as: "customer" } } });
|
|
196
|
+
assert.equal(
|
|
197
|
+
refusal(() => validateSchemaPayload(createJsonApiFieldsetsQueryValidator({ resource: flat, deferIncludedTypes: true }), {
|
|
198
|
+
fields: { regions: ["name"] }
|
|
199
|
+
}, { phase: "input" })).fieldErrorCodes?.["fields.regions"]?.code,
|
|
200
|
+
"crud.query.fieldsKeysInvalidWithAliases"
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
// The check takes the region's fields the include shows, and refuses any other field and any type it does not reach.
|
|
204
|
+
const check = createIncludedFieldsetsCheck(resource);
|
|
205
|
+
const includedTypes = new Map([["regions", new Set(["name", "code"])]]);
|
|
206
|
+
check({ orders: ["reference"], customers: ["name"], regions: ["name", "code"] }, includedTypes);
|
|
207
|
+
check(undefined, includedTypes);
|
|
208
|
+
const hidden = refusal(() => check({ regions: ["name", "secret"] }, includedTypes));
|
|
209
|
+
assert.equal(hidden.status, 400);
|
|
210
|
+
assert.deepEqual(hidden.details.fieldErrorCodes["fields.regions"], {
|
|
211
|
+
code: "crud.query.fieldsNotShown",
|
|
212
|
+
params: { type: "regions", shown: "name, code", fields: "secret" }
|
|
213
|
+
});
|
|
214
|
+
assert.equal(
|
|
215
|
+
hidden.details.fieldErrors["fields.regions"],
|
|
216
|
+
"fields[regions] may name only what this read's includes show of regions: name, code. It names secret."
|
|
217
|
+
);
|
|
218
|
+
const unrelated = refusal(() => check({ tags: ["label"] }, includedTypes));
|
|
219
|
+
assert.equal(unrelated.details.fieldErrorCodes["fields.tags"].code, "crud.query.fieldsKeysInvalidWithAliases");
|
|
220
|
+
assert.match(unrelated.details.fieldErrors["fields.tags"], /Allowed keys: "orders", "customers", "regions"\./u);
|
|
221
|
+
// Before boot resolves the types (or with no table resources), no such type is reached.
|
|
222
|
+
assert.equal(refusal(() => check({ regions: ["name"] }, new Map())).details.fieldErrorCodes["fields.regions"].code,
|
|
223
|
+
"crud.query.fieldsKeysInvalidWithAliases");
|
|
224
|
+
});
|
|
225
|
+
|
|
163
226
|
test("createCrudCursorPaginationQueryValidator keeps numeric cursor validation for unordered lists", () => {
|
|
164
227
|
const validator = createCrudCursorPaginationQueryValidator({});
|
|
165
228
|
|
|
@@ -86,9 +86,9 @@ test("a CRUD list refuses a query key it does not take, which Fastify's validati
|
|
|
86
86
|
test("a CRUD list takes filter[id], one record id or several, which a lookup sends to label the values it holds", async (t) => {
|
|
87
87
|
const { app, listed } = await listApp(t);
|
|
88
88
|
|
|
89
|
-
for (const url of ["/api/notes?filter%5Bid%5D=7", "/api/notes?filter%5Bid%5D=7&filter%5Bid%5D=12&page%5Blimit%5D=20"]) {
|
|
89
|
+
for (const url of ["/api/notes?filter%5Bid%5D=7", "/api/notes?filter%5Bid%5D=7&filter%5Bid%5D=12&page%5Blimit%5D=20", "/api/notes?filter%5Bid%5D=7,12"]) {
|
|
90
90
|
const response = await app.inject({ method: "GET", url });
|
|
91
91
|
assert.equal(response.statusCode, 200, `${url}: ${response.body}`);
|
|
92
92
|
}
|
|
93
|
-
assert.deepEqual(listed.map((input) => input.id), [["7"], ["7", "12"]]);
|
|
93
|
+
assert.deepEqual(listed.map((input) => input.id), [["7"], ["7", "12"], ["7", "12"]]);
|
|
94
94
|
});
|