@jskit-ai/crud-core 0.2.14 → 0.2.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/locales/en.json +1 -11
  3. package/package.json +19 -19
  4. package/patterns/{json-api-resource-package → crud-feature-package}/PATTERN.md +69 -37
  5. package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/package.json +5 -4
  6. package/patterns/crud-feature-package/example/packages/books/src/server/BooksFeature.js +13 -0
  7. package/patterns/crud-feature-package/example/packages/books/src/shared/bookResource.js +74 -0
  8. package/patterns/crud-feature-package/example/packages/books/src/shared/index.js +1 -0
  9. package/src/server/createHooksToCollectChildren.js +56 -34
  10. package/src/server/crudContracts.js +54 -0
  11. package/src/server/defineCrudFeature.js +509 -0
  12. package/src/server/jsonApiModule/actions.js +44 -30
  13. package/src/server/jsonApiModule/routes.js +2 -2
  14. package/src/server/jsonApiModule/service.js +213 -32
  15. package/src/server/jsonApiResourceContract.js +41 -1
  16. package/src/server/listQueryValidators.js +1 -1
  17. package/src/server/removedApi.js +87 -0
  18. package/src/server/types.js +26 -50
  19. package/test/assistantActionConformance.test.js +20 -21
  20. package/test/assistantPagination.integration.test.js +32 -42
  21. package/test/createHooksToCollectChildren.test.js +61 -16
  22. package/test/crudFeaturePackagePattern.test.js +50 -0
  23. package/test/crudOnHandles.test.js +454 -0
  24. package/test/{defineCrudJsonApiFeature.test.js → defineCrudFeature.test.js} +444 -141
  25. package/test/errorCodes.test.js +11 -52
  26. package/test/hiddenFields.test.js +62 -0
  27. package/test/listQueryValidators.test.js +1 -1
  28. package/test/routeContracts.test.js +1 -1
  29. package/test/support/crudJsonApiActionOptions.js +3 -3
  30. package/test/unservedCrudAutomation.test.js +27 -22
  31. package/patterns/json-api-resource-package/example/packages/books/src/server/BooksFeature.js +0 -13
  32. package/patterns/json-api-resource-package/example/packages/books/src/shared/bookResource.js +0 -83
  33. package/patterns/json-api-resource-package/example/packages/books/src/shared/index.js +0 -1
  34. package/src/server/createCrudServiceFromResource.js +0 -63
  35. package/src/server/defineCrudJsonApiFeature.js +0 -346
  36. package/src/server/fieldAccess.js +0 -298
  37. package/src/server/jsonApiModule/repository.js +0 -355
  38. package/src/server/lookupPathSupport.js +0 -58
  39. package/src/server/lookups.js +0 -40
  40. package/src/server/repositorySupport.js +0 -528
  41. package/src/server/resourceRuntime/compiledRuntime.js +0 -284
  42. package/src/server/resourceRuntime/index.js +0 -659
  43. package/src/server/resourceRuntime/listControls.js +0 -333
  44. package/src/server/resourceRuntime/lookupHydration.js +0 -626
  45. package/src/server/resourceRuntime/operationStages.js +0 -140
  46. package/src/server/resourceRuntime/recordValidation.js +0 -65
  47. package/src/server/serviceMethods.js +0 -149
  48. package/test/createCrudServiceFromResource.test.js +0 -323
  49. package/test/fieldAccess.test.js +0 -86
  50. package/test/jsonApiRepository.test.js +0 -333
  51. package/test/jsonApiRepositoryDataCosts.test.js +0 -183
  52. package/test/jsonApiRepositoryPageLimits.test.js +0 -158
  53. package/test/jsonApiRepositoryRowLocks.test.js +0 -137
  54. package/test/jsonApiResourcePackagePattern.test.js +0 -20
  55. package/test/lookups.test.js +0 -111
  56. package/test/repositorySupport.test.js +0 -767
  57. package/test/resourceRuntime.test.js +0 -1014
  58. package/test/serviceMethods.test.js +0 -139
  59. /package/patterns/{json-api-resource-package → crud-feature-package}/example/migrations/20260815000000_books.cjs +0 -0
  60. /package/patterns/{json-api-resource-package → crud-feature-package}/example/packages/books/src/server/types.js +0 -0
@@ -1,86 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { createFieldAccessForRoleMatrix } from "../src/server/fieldAccess.js";
4
-
5
- test("createFieldAccessForRoleMatrix resolves role and action policies", () => {
6
- const fieldAccess = createFieldAccessForRoleMatrix({
7
- default: {
8
- readable: {
9
- list: ["id", "name"],
10
- "*": ["id"]
11
- },
12
- writable: {
13
- create: ["name"],
14
- update: ["name"]
15
- }
16
- },
17
- admin: {
18
- readable: "*",
19
- writable: "*"
20
- },
21
- writeMode: "strip"
22
- });
23
-
24
- assert.equal(fieldAccess.writeMode, "strip");
25
- assert.deepEqual(
26
- fieldAccess.readable({
27
- action: "list",
28
- context: { auth: { role: "user" } }
29
- }),
30
- ["id", "name"]
31
- );
32
- assert.deepEqual(
33
- fieldAccess.readable({
34
- action: "view",
35
- context: { auth: { role: "user" } }
36
- }),
37
- ["id"]
38
- );
39
- assert.equal(
40
- fieldAccess.writable({
41
- action: "update",
42
- context: { auth: { role: "admin" } }
43
- }),
44
- "*"
45
- );
46
- });
47
-
48
- test("createFieldAccessForRoleMatrix supports function policies and default role fallback", () => {
49
- const fieldAccess = createFieldAccessForRoleMatrix({
50
- default: {
51
- readable: ({ action }) => (action === "list" ? ["id"] : ["id", "name"]),
52
- writable: {
53
- "*": ["name"]
54
- }
55
- }
56
- });
57
-
58
- assert.deepEqual(
59
- fieldAccess.readable({
60
- action: "list",
61
- context: { auth: { role: "unknown" } }
62
- }),
63
- ["id"]
64
- );
65
- assert.deepEqual(
66
- fieldAccess.readable({
67
- action: "view",
68
- context: { auth: { role: "unknown" } }
69
- }),
70
- ["id", "name"]
71
- );
72
- assert.deepEqual(
73
- fieldAccess.writable({
74
- action: "update",
75
- context: { auth: { role: "unknown" } }
76
- }),
77
- ["name"]
78
- );
79
- });
80
-
81
- test("createFieldAccessForRoleMatrix validates writeMode", () => {
82
- assert.throws(
83
- () => createFieldAccessForRoleMatrix({ writeMode: "invalid-mode" }),
84
- /fieldAccess\.writeMode must be "throw" or "strip"/
85
- );
86
- });
@@ -1,333 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import test from "node:test";
3
- import knexLib from "knex";
4
- import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
- import {
6
- createJsonRestApiHost,
7
- createJsonRestResourceScopeOptions
8
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
9
- import { defineCrudResource } from "@jskit-ai/resource-crud-core/shared/crudResource";
10
- import { createCrudJsonApiActions } from "../src/server/jsonApiModule/actions.js";
11
- import { crudJsonApiActionOptions } from "./support/crudJsonApiActionOptions.js";
12
- import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
13
- import { createCrudJsonApiService } from "../src/server/jsonApiModule/service.js";
14
-
15
- function deadlockVictim() {
16
- return Object.assign(new Error("Deadlock found when trying to get lock; try restarting transaction"), {
17
- code: "ER_LOCK_DEADLOCK",
18
- errno: 1213
19
- });
20
- }
21
-
22
- function createRepositoryRecorder() {
23
- const calls = [];
24
- const response = { data: { type: "books", id: "7", attributes: { title: "Dune" } } };
25
- const resource = {
26
- schema: {
27
- title: { type: "string" },
28
- authorId: { type: "id", belongsTo: "authors", as: "author" }
29
- }
30
- };
31
- const api = { resources: { books: {} }, transaction: (work) => work("managed") };
32
- for (const method of ["get", "query", "post", "patch", "delete"]) {
33
- api.resources.books[method] = async (params, context) => {
34
- calls.push({ method, params, context });
35
- return response;
36
- };
37
- }
38
- return {
39
- calls,
40
- response,
41
- repository: createCrudJsonApiRepository({ api, resource, resourceScopeName: "books" })
42
- };
43
- }
44
-
45
- test("JSON:API repositories use plain input with explicit document responses", async () => {
46
- const { repository, calls, response } = createRepositoryRecorder();
47
- const context = Object.freeze({ scopeValues: Object.freeze({ workspaceId: "2" }) });
48
- const payload = Object.freeze({ title: "Dune", authorId: 9, data: { edition: 1 } });
49
- assert.equal(await repository.createDocument(payload, { trx: "managed", context }), response);
50
- assert.deepEqual(calls[0].params, {
51
- data: { title: "Dune", author: 9, data: { edition: 1 } },
52
- returning: "full",
53
- transaction: "managed",
54
- format: "jsonapi"
55
- });
56
- assert.notEqual(calls[0].context, context);
57
- assert.notEqual(calls[0].context.scopeValues, context.scopeValues);
58
- assert.equal(payload.authorId, 9);
59
- assert.equal(await repository.patchDocumentById("7", { authorId: null }), response);
60
- assert.deepEqual(calls[1].params, {
61
- id: "7",
62
- data: { author: null },
63
- returning: "full",
64
- transaction: null,
65
- format: "jsonapi"
66
- });
67
- await assert.rejects(
68
- () => repository.createDocument({ authorId: "9", author: "10" }),
69
- /Provide either "authorId" or "author", not both/
70
- );
71
- assert.equal(calls.length, 2);
72
- });
73
-
74
- test("JSON:API repository reads and empty patches retain their document contract", async () => {
75
- const { repository, calls, response } = createRepositoryRecorder();
76
- assert.equal(await repository.queryDocuments({ title: "Dune" }), response);
77
- assert.equal(await repository.patchDocumentById("7", {}), response);
78
- assert.equal(await repository.deleteDocumentById("7"), null);
79
- assert.deepEqual(calls.map(({ method, params }) => ({ method, params })), [
80
- { method: "query", params: { queryParams: { filters: { title: "Dune" } }, transaction: null, format: "jsonapi" } },
81
- { method: "get", params: { id: "7", queryParams: {}, transaction: null, format: "jsonapi" } },
82
- { method: "delete", params: { id: "7", returning: "none", transaction: null, format: "jsonapi" } }
83
- ]);
84
- assert.equal(await repository.withTransaction((trx) => trx), "managed");
85
- });
86
-
87
- async function createDatabaseRepository(t) {
88
- const knex = knexLib({
89
- client: "better-sqlite3",
90
- connection: { filename: ":memory:" },
91
- useNullAsDefault: true
92
- });
93
- t.after(() => knex.destroy());
94
- await knex.schema.createTable("books", (table) => {
95
- table.increments("id");
96
- table.string("title").notNullable();
97
- });
98
- await knex.schema.createTable("audit_entries", (table) => {
99
- table.increments("id");
100
- table.string("message").notNullable();
101
- });
102
- const api = await createJsonRestApiHost({ knex, logger: silentLogger });
103
- const resource = { tableName: "books", schema: { title: { type: "string", required: true } } };
104
- await api.addResource("books", createJsonRestResourceScopeOptions(resource));
105
- const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "books" });
106
- return { api, knex, repository };
107
- }
108
-
109
- test("repository transactions commit resource writes and raw SQL before completion hooks", async (t) => {
110
- const { api, knex, repository } = await createDatabaseRepository(t);
111
- const committed = [];
112
- await api.customize({ hooks: { afterCommit: ({ context }) => committed.push(context.method) } });
113
- const document = await repository.withTransaction(async (trx) => {
114
- const first = await repository.createDocument({ title: "Dune" }, { trx });
115
- await repository.createDocument({ title: "Kindred" }, { trx });
116
- await trx("audit_entries").insert({ message: "Created books" });
117
- assert.deepEqual(committed, []);
118
- return first;
119
- });
120
- assert.equal(document.data.attributes.title, "Dune");
121
- assert.deepEqual(await knex("books").orderBy("id").pluck("title"), ["Dune", "Kindred"]);
122
- assert.deepEqual(await knex("audit_entries").pluck("message"), ["Created books"]);
123
- assert.deepEqual(committed, ["post", "post"]);
124
- });
125
-
126
- test("a deadlock victim's repository transaction runs again and commits its writes once", async (t) => {
127
- const { knex, repository } = await createDatabaseRepository(t);
128
- let attempts = 0;
129
- const document = await repository.withTransaction(async (trx) => {
130
- attempts += 1;
131
- const created = await repository.createDocument({ title: "Dune" }, { trx });
132
- await trx("audit_entries").insert({ message: `Attempt ${attempts}` });
133
- if (attempts === 1) {
134
- throw deadlockVictim();
135
- }
136
- return created;
137
- });
138
- assert.equal(attempts, 2);
139
- assert.equal(document.data.attributes.title, "Dune");
140
- assert.deepEqual(await knex("books").pluck("title"), ["Dune"]);
141
- assert.deepEqual(await knex("audit_entries").pluck("message"), ["Attempt 2"]);
142
- });
143
-
144
- test("a write that owns its transaction runs again after a deadlock; one in a caller's transaction does not", async () => {
145
- let posts = 0;
146
- const api = {
147
- resources: {
148
- books: {
149
- async post() {
150
- posts += 1;
151
- if (posts === 1) {
152
- throw deadlockVictim();
153
- }
154
- return { data: { type: "books", id: String(posts) } };
155
- }
156
- }
157
- }
158
- };
159
- const repository = createCrudJsonApiRepository({ api, resource: { schema: {} }, resourceScopeName: "books" });
160
- assert.equal((await repository.createDocument({ title: "Dune" })).data.id, "2");
161
- posts = 0;
162
- await assert.rejects(repository.createDocument({ title: "Dune" }, { trx: "managed" }), { code: "ER_LOCK_DEADLOCK" });
163
- assert.equal(posts, 1);
164
- });
165
-
166
- test("repository transactions roll back resource writes and raw SQL after a rejected participant", async (t) => {
167
- const { knex, repository } = await createDatabaseRepository(t);
168
- await assert.rejects(
169
- () => repository.withTransaction(async (trx) => {
170
- await repository.createDocument({ title: "Dune" }, { trx });
171
- await trx("audit_entries").insert({ message: "Pending" });
172
- await repository.createDocument({}, { trx });
173
- }),
174
- (error) => error.transactionOutcome === "rolledBack" && error.code === "REST_API_VALIDATION"
175
- );
176
- assert.deepEqual(await knex("books"), []);
177
- assert.deepEqual(await knex("audit_entries"), []);
178
- });
179
-
180
- test("a missing write inside a managed transaction cannot become a successful null result", async (t) => {
181
- const { knex, repository } = await createDatabaseRepository(t);
182
- await assert.rejects(
183
- () => repository.withTransaction(async (trx) => {
184
- await repository.createDocument({ title: "Dune" }, { trx });
185
- return repository.patchDocumentById("999", { title: "Missing" }, { trx });
186
- }),
187
- (error) => error.transactionOutcome === "rolledBack" && error.subtype === "not_found"
188
- );
189
- assert.deepEqual(await knex("books"), []);
190
- assert.equal(await repository.patchDocumentById("999", { title: "Missing" }), null);
191
- });
192
-
193
- test("repository writes reject a raw transaction owner without inserting data", async (t) => {
194
- const { knex, repository } = await createDatabaseRepository(t);
195
- await knex.transaction(async (trx) => {
196
- await assert.rejects(
197
- () => repository.createDocument({ title: "Dune" }, { trx }),
198
- (error) => error.code === "REST_API_VALIDATION" && error.transactionOutcome === "none"
199
- );
200
- assert.deepEqual(await trx("books"), []);
201
- });
202
- assert.deepEqual(await knex("books"), []);
203
- });
204
-
205
- test("a failing CRUD afterCommit hook reports committed and leaves the actual write stored", async (t) => {
206
- const { knex, repository } = await createDatabaseRepository(t);
207
- const book = await repository.createDocument({ title: "Dune" });
208
- const failure = Object.freeze(new Error("Notification failed"));
209
- const actions = createCrudJsonApiActions(crudJsonApiActionOptions({
210
- namespace: "books",
211
- resource: defineCrudResource({
212
- namespace: "books",
213
- tableName: "books",
214
- autofilter: "public",
215
- schema: {
216
- title: {
217
- type: "string",
218
- required: true,
219
- operations: { output: { required: true }, create: { required: true }, patch: { required: false } }
220
- }
221
- }
222
- }),
223
- repository,
224
- service: createCrudJsonApiService({ repository }),
225
- surface: "app",
226
- operations: ["update"],
227
- permissionForOperation: () => ({ require: "authenticated" }),
228
- operationLifecycle: { update: { afterCommit() { throw failure; } } }
229
- }));
230
- await assert.rejects(
231
- () => actions[0].execute({ recordId: book.data.id, title: "Kindred" }, {}),
232
- (error) => error.transactionOutcome === "committed" && error.cause === failure
233
- );
234
- assert.equal((await knex("books").where({ id: book.data.id }).first()).title, "Kindred");
235
- });
236
-
237
- async function createLockedNotesRepository(t, { lockVersionField = "lockVersion" } = {}) {
238
- const knex = knexLib({
239
- client: "better-sqlite3",
240
- connection: { filename: ":memory:" },
241
- useNullAsDefault: true
242
- });
243
- t.after(() => knex.destroy());
244
- await knex.schema.createTable("notes", (table) => {
245
- table.increments("id");
246
- table.integer("workspace_id").notNullable();
247
- table.string("title").notNullable();
248
- table.integer("lock_version").notNullable().defaultTo(0);
249
- });
250
- await knex.schema.createTable("audit_entries", (table) => {
251
- table.increments("id");
252
- table.string("message").notNullable();
253
- });
254
- await knex("notes").insert([
255
- { workspace_id: 1, title: "Dune", lock_version: 3 },
256
- { workspace_id: 2, title: "Kindred", lock_version: 0 }
257
- ]);
258
- const resource = defineCrudResource({
259
- namespace: "notes",
260
- tableName: "notes",
261
- autofilter: "workspace",
262
- lockVersionField,
263
- schema: {
264
- workspaceId: { type: "id", required: true, hidden: true, column: "workspace_id" },
265
- title: { type: "string", required: true },
266
- lockVersion: { type: "integer", min: 0, readOnly: true, column: "lock_version" }
267
- }
268
- });
269
- const api = await createJsonRestApiHost({ knex, logger: silentLogger });
270
- await api.addResource("notes", createJsonRestResourceScopeOptions(resource));
271
- const repository = createCrudJsonApiRepository({ api, resource, resourceScopeName: "notes" });
272
- const stored = (id) => knex("notes").where({ id }).first("title", "lock_version");
273
- return { knex, repository, stored };
274
- }
275
-
276
- const WORKSPACE_ONE = Object.freeze({ context: Object.freeze({ scopeValues: Object.freeze({ workspaceId: "1" }) }) });
277
-
278
- test("a patch at the record's lock version applies and moves the lock version on by one", async (t) => {
279
- const { repository, stored } = await createLockedNotesRepository(t);
280
- const document = await repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, WORKSPACE_ONE);
281
- assert.equal(document.data.attributes.title, "Dune Messiah");
282
- assert.equal(document.data.attributes.lockVersion, 4);
283
- assert.deepEqual(await stored(1), { title: "Dune Messiah", lock_version: 4 });
284
- assert.equal((await repository.patchDocumentIfLockVersion("1", 4, {}, WORKSPACE_ONE)).data.attributes.lockVersion, 5);
285
- });
286
-
287
- test("a patch at a stale lock version rejects with a lock version conflict and changes nothing", async (t) => {
288
- const { repository, stored } = await createLockedNotesRepository(t);
289
- await assert.rejects(
290
- () => repository.patchDocumentIfLockVersion("1", 2, { title: "Dune Messiah" }, WORKSPACE_ONE),
291
- (error) => error.status === 409 && error.code === "crud.document.lockVersionConflict" &&
292
- error.message === "This record changed. Reload and try again."
293
- );
294
- assert.deepEqual(await stored(1), { title: "Dune", lock_version: 3 });
295
- });
296
-
297
- test("a record that is missing or out of scope patches to null and keeps its lock version", async (t) => {
298
- const { repository, stored } = await createLockedNotesRepository(t);
299
- assert.equal(await repository.patchDocumentIfLockVersion("2", 0, { title: "Fledgling" }, WORKSPACE_ONE), null);
300
- assert.equal(await repository.patchDocumentIfLockVersion("9", 0, { title: "Fledgling" }, WORKSPACE_ONE), null);
301
- assert.deepEqual(await stored(2), { title: "Kindred", lock_version: 0 });
302
- });
303
-
304
- test("a lock-version patch joins the caller's transaction and rolls back with it", async (t) => {
305
- const { knex, repository, stored } = await createLockedNotesRepository(t);
306
- await assert.rejects(() => repository.withTransaction(async (trx) => {
307
- await repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, { ...WORKSPACE_ONE, trx });
308
- await trx("audit_entries").insert({ message: "Renamed" });
309
- assert.deepEqual(await trx("notes").where({ id: 1 }).first("title", "lock_version"), { title: "Dune Messiah", lock_version: 4 });
310
- throw new Error("Abandon the rename");
311
- }), /Abandon the rename/);
312
- assert.deepEqual(await stored(1), { title: "Dune", lock_version: 3 });
313
- assert.deepEqual(await knex("audit_entries"), []);
314
- await repository.withTransaction((trx) => repository.patchDocumentIfLockVersion("1", 3, { title: "Dune Messiah" }, { ...WORKSPACE_ONE, trx }));
315
- assert.deepEqual(await stored(1), { title: "Dune Messiah", lock_version: 4 });
316
- });
317
-
318
- test("patchDocumentIfLockVersion needs a lockVersionField, a whole expected version and a patch without the lock", async (t) => {
319
- const { repository } = await createLockedNotesRepository(t);
320
- const unlocked = createCrudJsonApiRepository({
321
- api: { resources: {} },
322
- resource: { schema: {} },
323
- resourceScopeName: "notes"
324
- });
325
- await assert.rejects(() => unlocked.patchDocumentIfLockVersion("1", 0, {}), /needs resource "notes" to name its lockVersionField/);
326
- for (const expected of [-1, 1.5, "3", null]) {
327
- await assert.rejects(() => repository.patchDocumentIfLockVersion("1", expected, {}, WORKSPACE_ONE), /must be a non-negative integer/);
328
- }
329
- await assert.rejects(
330
- () => repository.patchDocumentIfLockVersion("1", 3, { lockVersion: 9 }, WORKSPACE_ONE),
331
- /advances lockVersion itself, so the patch must leave it out/
332
- );
333
- });
@@ -1,183 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import test from "node:test";
3
- import knexLib from "knex";
4
- import { silentLogger } from "@jskit-ai/kernel/server/runtime/logger";
5
- import {
6
- createJsonRestApiHost,
7
- createJsonRestResourceScopeOptions
8
- } from "@jskit-ai/json-rest-api-core/server/jsonRestApiHost";
9
- import { createCrudJsonApiRepository } from "../src/server/jsonApiModule/repository.js";
10
-
11
- // People in teams, parents owned by people, and children of parents, each read
12
- // through a row policy for the context's team, as a real application's are.
13
- const resources = {
14
- people: {
15
- tableName: "people",
16
- schema: { id: { type: "id", primary: true }, name: { type: "string" }, team: { type: "string" } }
17
- },
18
- parents: {
19
- tableName: "parents",
20
- schema: {
21
- id: { type: "id", primary: true },
22
- title: { type: "string" },
23
- ownerId: { type: "id", belongsTo: "people", as: "owner" }
24
- }
25
- },
26
- children: {
27
- tableName: "children",
28
- schema: {
29
- id: { type: "id", primary: true },
30
- parentId: { type: "id", belongsTo: "parents", as: "parent" },
31
- authorId: { type: "id", belongsTo: "people", as: "author" },
32
- title: { type: "string" }
33
- }
34
- }
35
- };
36
-
37
- async function createFixture(t) {
38
- const knex = knexLib({ client: "better-sqlite3", connection: { filename: ":memory:" }, useNullAsDefault: true });
39
- t.after(() => knex.destroy());
40
- await knex.schema.createTable("people", (table) => { table.increments("id"); table.string("name"); table.string("team"); });
41
- await knex.schema.createTable("parents", (table) => { table.increments("id"); table.string("title"); table.integer("owner_id"); });
42
- await knex.schema.createTable("children", (table) => {
43
- table.increments("id"); table.integer("parent_id"); table.integer("author_id"); table.string("title");
44
- });
45
- await knex("people").insert([{ name: "Ada", team: "a" }, { name: "Bea", team: "b" }]);
46
- await knex("parents").insert([{ title: "Visible", owner_id: 1 }, { title: "Hidden", owner_id: 2 }]);
47
-
48
- const policyRuns = [];
49
- const team = (context) => context?.team || "__none__";
50
- const policies = {
51
- people: ({ query, context, column }) => {
52
- query.where(column("team"), team(context));
53
- return true;
54
- },
55
- parents: ({ query, context, column }) => {
56
- query.whereExists(function visibleOwner() {
57
- this.select(1).from("people as owner").whereRaw("owner.id = ??", [column("ownerId")]).where("owner.team", team(context));
58
- });
59
- return true;
60
- },
61
- children: ({ query, context, column }) => {
62
- query.whereExists(function visibleParent() {
63
- this.select(1).from("parents as parent").join("people as owner", "owner.id", "parent.owner_id")
64
- .whereRaw("parent.id = ??", [column("parentId")]).where("owner.team", team(context));
65
- });
66
- return true;
67
- }
68
- };
69
- const api = await createJsonRestApiHost({ knex, logger: silentLogger });
70
- for (const [name, resource] of Object.entries(resources)) {
71
- await api.addResource(name, createJsonRestResourceScopeOptions(resource, {
72
- rowPolicy: (args) => {
73
- policyRuns.push(`${name}:${args.queryPurpose}`);
74
- return policies[name](args);
75
- }
76
- }));
77
- }
78
- const children = createCrudJsonApiRepository({ api, resource: resources.children, resourceScopeName: "children" });
79
-
80
- // Statements and row-policy runs of one operation; BEGIN and COMMIT counted apart.
81
- async function measure(run) {
82
- const counts = { statements: 0, transactionStatements: 0, policy: {} };
83
- const onQuery = ({ sql }) => {
84
- if (/^(begin|commit|rollback|savepoint|release)/iu.test(sql.trim())) {
85
- counts.transactionStatements += 1;
86
- } else {
87
- counts.statements += 1;
88
- }
89
- };
90
- policyRuns.length = 0;
91
- knex.on("query", onQuery);
92
- try {
93
- counts.result = await run();
94
- } finally {
95
- knex.removeListener("query", onQuery);
96
- }
97
- for (const run of policyRuns) {
98
- counts.policy[run] = (counts.policy[run] || 0) + 1;
99
- }
100
- return counts;
101
- }
102
-
103
- return { knex, api, children, measure };
104
- }
105
-
106
- const context = Object.freeze({ team: "a" });
107
- const childPayloads = (count) => Array.from({ length: count }, (_, index) => ({ parentId: 1, authorId: 1, title: `Child ${index}` }));
108
-
109
- test("createDocuments writes a batch in one transaction and reads no record back", async (t) => {
110
- const { knex, children, measure } = await createFixture(t);
111
- const small = await measure(() => children.createDocuments(childPayloads(10), { context }));
112
- const large = await measure(() => children.createDocuments(childPayloads(100), { context }));
113
-
114
- assert.deepEqual(large.result.slice(0, 2), [
115
- { data: { type: "children", id: "11" } },
116
- { data: { type: "children", id: "12" } }
117
- ]);
118
- assert.equal(await knex("children").count({ count: "*" }).first().then(({ count }) => Number(count)), 110);
119
- for (const batch of [small, large]) {
120
- // One owned transaction for the whole batch, whatever its size.
121
- assert.equal(batch.transactionStatements, 2);
122
- // No read-back: no get preflight and no visibility check of the new rows' links.
123
- assert.equal(batch.policy["children:relationship-identifiers"], undefined);
124
- assert.equal(batch.policy["parents:relationship-identifiers"], undefined);
125
- assert.equal(batch.policy["people:relationship-identifiers"], undefined);
126
- }
127
- });
128
-
129
- test("returning minimal or none skips the read-back that returning full pays per created row", async (t) => {
130
- const { children, measure } = await createFixture(t);
131
- const perRow = {};
132
- for (const returning of ["full", "minimal", "none"]) {
133
- const counts = [];
134
- for (const size of [10, 50]) {
135
- const measured = await measure(() => children.withTransaction(async (trx) => {
136
- for (const payload of childPayloads(size)) {
137
- await children.createDocument(payload, { trx, context, returning });
138
- }
139
- }));
140
- counts.push(measured);
141
- }
142
- // Per-row cost: the difference between 50 and 10 rows, over 40 rows.
143
- perRow[returning] = (counts[1].statements - counts[0].statements) / 40;
144
- const linkageRuns = Object.entries(counts[1].policy)
145
- .filter(([run]) => run.endsWith(":relationship-identifiers"))
146
- .reduce((sum, [, runs]) => sum + runs, 0);
147
- assert.equal(linkageRuns, returning === "full" ? 100 : 0, `${returning} linkage checks`);
148
- }
149
- // The read-back is a get: its preflight, its read and one visibility check per linked type.
150
- assert.ok(perRow.full - perRow.minimal >= 4, JSON.stringify(perRow));
151
- assert.equal(perRow.minimal, perRow.none, JSON.stringify(perRow));
152
- });
153
-
154
- test("createDocuments results follow the payloads, and a failing payload leaves none created", async (t) => {
155
- const { knex, children } = await createFixture(t);
156
- const full = await children.createDocuments(childPayloads(2), { context, returning: "full" });
157
- assert.deepEqual(full.map((document) => document.data.attributes.title), ["Child 0", "Child 1"]);
158
- assert.deepEqual(await children.createDocuments(childPayloads(2), { context, returning: "none" }), [undefined, undefined]);
159
-
160
- // The second payload links a parent the reader cannot see, so the batch rolls back.
161
- await assert.rejects(
162
- () => children.createDocuments([{ parentId: 1, authorId: 1, title: "Kept?" }, { parentId: 2, authorId: 1, title: "Hidden parent" }], { context }),
163
- /non-existent parents with id 2/
164
- );
165
- assert.equal(await knex("children").where({ title: "Kept?" }).first(), undefined);
166
- await assert.rejects(() => children.createDocuments({ title: "Not a list" }), /requires an array of payloads/);
167
- await assert.rejects(() => children.createDocument({ title: "x" }, { returning: "ids" }), /returning must be "full", "minimal" or "none"/);
168
- });
169
-
170
- test("patchDocumentById with returning minimal answers the identifier, and null for a record out of scope", async (t) => {
171
- const { children } = await createFixture(t);
172
- const [{ data: created }] = await children.createDocuments(childPayloads(1), { context });
173
- assert.deepEqual(
174
- await children.patchDocumentById(created.id, { title: "Renamed" }, { context, returning: "minimal" }),
175
- { data: { type: "children", id: created.id } }
176
- );
177
- assert.deepEqual(
178
- await children.patchDocumentById(created.id, {}, { context, returning: "minimal" }),
179
- { data: { type: "children", id: created.id } }
180
- );
181
- assert.equal(await children.patchDocumentById(created.id, { title: "Other team" }, { context: { team: "b" }, returning: "none" }), null);
182
- assert.equal((await children.getDocumentById(created.id, {}, { context })).data.attributes.title, "Renamed");
183
- });