@terreno/api 58.0.5 → 58.1.0

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 (75) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -0,0 +1,1256 @@
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
+ import type express from "express";
3
+ import {DateTime} from "luxon";
4
+ import mongoose from "mongoose";
5
+ import supertest from "supertest";
6
+ import type TestAgent from "supertest/lib/agent";
7
+ import {modelRouter, validateModelRouterBody} from "./api";
8
+ import {AuditApp} from "./audit/auditApp";
9
+ import {flushAuditRecorderForTests, resetAuditRecorderForTests} from "./audit/record";
10
+ import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
11
+ import {toBulkItemError} from "./bulk";
12
+ import {apiUnauthorizedMiddleware, isAPIError} from "./errors";
13
+ import {configureOpenApiValidator, resetOpenApiValidatorConfig} from "./openApiValidator";
14
+ import {Permissions} from "./permissions";
15
+ import {createdUpdatedPlugin, type IsDeleted, isDeletedPlugin} from "./plugins";
16
+ import {clearSyncRegistry, registerSync} from "./sync/registry";
17
+ import {syncPlugin} from "./sync/syncSeqPlugin";
18
+ import {TerrenoApp} from "./terrenoApp";
19
+ import {authAsUser, type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
20
+
21
+ const allPermissions = {
22
+ create: [Permissions.IsAuthenticated],
23
+ delete: [Permissions.IsAuthenticated],
24
+ list: [Permissions.IsAuthenticated],
25
+ read: [Permissions.IsAuthenticated],
26
+ update: [Permissions.IsAuthenticated],
27
+ };
28
+
29
+ type RouterOptions = Parameters<typeof modelRouter<Food>>[1];
30
+
31
+ const volatileKeys = ["_id", "id", "created", "updated", "__v"];
32
+
33
+ const stripVolatile = (value: Record<string, unknown>): Record<string, unknown> => {
34
+ const copy = {...value};
35
+ for (const key of volatileKeys) {
36
+ delete copy[key];
37
+ }
38
+ return copy;
39
+ };
40
+
41
+ const bulkFoodNames = async (): Promise<string[]> => {
42
+ const docs = await FoodModel.find({name: /^bulk-/}).sort({name: 1});
43
+ return docs.map((doc) => doc.name as string);
44
+ };
45
+
46
+ describe("modelRouter bulk", () => {
47
+ let app: express.Application;
48
+ let server: TestAgent;
49
+
50
+ const mountFoodRouter = (options: Partial<RouterOptions>): void => {
51
+ app.use(
52
+ "/food",
53
+ modelRouter(FoodModel, {
54
+ permissions: allPermissions,
55
+ ...options,
56
+ } as RouterOptions)
57
+ );
58
+ app.use(apiUnauthorizedMiddleware);
59
+ // Terminal handler so an unmatched route answers 404 instead of hanging.
60
+ app.use((_req: express.Request, res: express.Response) => {
61
+ res.status(404).json({title: "Not Found"});
62
+ });
63
+ };
64
+
65
+ beforeEach(async () => {
66
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
67
+ await setupDb();
68
+ await FoodModel.deleteMany({});
69
+ app = getBaseServer();
70
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
71
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
72
+ server = supertest(app);
73
+ });
74
+
75
+ afterEach(() => {
76
+ resetOpenApiValidatorConfig();
77
+ });
78
+
79
+ describe("mounting", () => {
80
+ it("does not mount POST /food/bulk when bulk is not enabled", async () => {
81
+ mountFoodRouter({});
82
+ const agent = await authAsUser(app, "notAdmin");
83
+ const res = await agent
84
+ .post("/food/bulk")
85
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]});
86
+ expect(res.status).toBe(404);
87
+ expect(await bulkFoodNames()).toEqual([]);
88
+ });
89
+
90
+ it("does not mount POST /food/bulk when bulk is false", async () => {
91
+ mountFoodRouter({bulk: false} as Partial<RouterOptions>);
92
+ const agent = await authAsUser(app, "notAdmin");
93
+ const res = await agent
94
+ .post("/food/bulk")
95
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]});
96
+ expect(res.status).toBe(404);
97
+ });
98
+
99
+ it("throws at registration when bulk is enabled and collectionActions.bulk exists", () => {
100
+ expect(() =>
101
+ modelRouter(FoodModel, {
102
+ bulk: true,
103
+ collectionActions: {
104
+ bulk: {
105
+ handler: async () => ({count: 1}),
106
+ method: "POST",
107
+ permissions: [Permissions.IsAny],
108
+ },
109
+ },
110
+ permissions: allPermissions,
111
+ } as RouterOptions)
112
+ ).toThrow("collectionAction 'bulk' collides with the bulk endpoint on /bulk");
113
+ });
114
+
115
+ it("still allows a bulk collection action when bulk is not enabled", async () => {
116
+ mountFoodRouter({
117
+ allowAnonymous: true,
118
+ collectionActions: {
119
+ bulk: {
120
+ handler: async () => ({count: 1}),
121
+ method: "POST",
122
+ permissions: [Permissions.IsAny],
123
+ },
124
+ },
125
+ });
126
+ const res = await server.post("/food/bulk").send({}).expect(200);
127
+ expect(res.body.data).toEqual({count: 1});
128
+ });
129
+
130
+ it("returns 401 without a token on a non-anonymous router", async () => {
131
+ mountFoodRouter({bulk: true} as Partial<RouterOptions>);
132
+ await server
133
+ .post("/food/bulk")
134
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]})
135
+ .expect(401);
136
+ expect(await bulkFoodNames()).toEqual([]);
137
+ });
138
+ });
139
+
140
+ describe("partial-mode create", () => {
141
+ it("creates each item, returns 201 entries in order, and matches POST /food data", async () => {
142
+ mountFoodRouter({bulk: true} as Partial<RouterOptions>);
143
+ const agent = await authAsUser(app, "notAdmin");
144
+ const res = await agent
145
+ .post("/food/bulk")
146
+ .send({
147
+ atomic: false,
148
+ operations: [
149
+ {body: {calories: 5, name: "bulk-a"}, method: "create"},
150
+ {body: {calories: 6, name: "bulk-b"}, method: "create"},
151
+ ],
152
+ })
153
+ .expect(200);
154
+ expect(res.body.data).toHaveLength(2);
155
+ expect(res.body.data.map((entry: {status: number}) => entry.status)).toEqual([201, 201]);
156
+ expect(res.body.data.map((entry: {index: number}) => entry.index)).toEqual([0, 1]);
157
+ expect(res.body.data.map((entry: {method: string}) => entry.method)).toEqual([
158
+ "create",
159
+ "create",
160
+ ]);
161
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
162
+ expect(res.body.data[0].id).toBe(res.body.data[0].data._id);
163
+
164
+ // Test fix (Pick): Food derives `description` from `name`, so compare against a single
165
+ // POST with the same body instead of renaming a differently named doc.
166
+ const single = await agent.post("/food").send({calories: 5, name: "bulk-a"}).expect(201);
167
+ expect(stripVolatile(res.body.data[0].data)).toEqual(stripVolatile(single.body.data));
168
+ });
169
+
170
+ it("runs preCreate for every item", async () => {
171
+ mountFoodRouter({
172
+ bulk: true,
173
+ preCreate: (body: Partial<Food>) => ({...body, calories: 14}),
174
+ } as Partial<RouterOptions>);
175
+ const agent = await authAsUser(app, "notAdmin");
176
+ await agent
177
+ .post("/food/bulk")
178
+ .send({
179
+ atomic: false,
180
+ operations: [
181
+ {body: {calories: 1, name: "bulk-a"}, method: "create"},
182
+ {body: {calories: 2, name: "bulk-b"}, method: "create"},
183
+ ],
184
+ })
185
+ .expect(200);
186
+ const docs = await FoodModel.find({name: /^bulk-/});
187
+ expect(docs).toHaveLength(2);
188
+ expect(docs.map((doc) => doc.calories)).toEqual([14, 14]);
189
+ });
190
+
191
+ it("reports 403 'Create not allowed' for an item whose preCreate returns null", async () => {
192
+ mountFoodRouter({
193
+ bulk: true,
194
+ preCreate: (body: Partial<Food>) => (body.name === "bulk-b" ? null : body),
195
+ } as Partial<RouterOptions>);
196
+ const agent = await authAsUser(app, "notAdmin");
197
+ const res = await agent
198
+ .post("/food/bulk")
199
+ .send({
200
+ atomic: false,
201
+ operations: [
202
+ {body: {name: "bulk-a"}, method: "create"},
203
+ {body: {name: "bulk-b"}, method: "create"},
204
+ ],
205
+ })
206
+ .expect(200);
207
+ expect(res.body.data[0].status).toBe(201);
208
+ expect(res.body.data[1].status).toBe(403);
209
+ expect(res.body.data[1].index).toBe(1);
210
+ expect(res.body.data[1].error.title).toBe("Create not allowed");
211
+ expect(await bulkFoodNames()).toEqual(["bulk-a"]);
212
+ });
213
+
214
+ it("reports 405 for every item when the user fails the create permission", async () => {
215
+ mountFoodRouter({
216
+ bulk: true,
217
+ permissions: {...allPermissions, create: [Permissions.IsAdmin]},
218
+ } as Partial<RouterOptions>);
219
+ const agent = await authAsUser(app, "notAdmin");
220
+ const res = await agent
221
+ .post("/food/bulk")
222
+ .send({
223
+ atomic: false,
224
+ operations: [
225
+ {body: {name: "bulk-a"}, method: "create"},
226
+ {body: {name: "bulk-b"}, method: "create"},
227
+ ],
228
+ })
229
+ .expect(200);
230
+ expect(res.body.data.map((entry: {status: number}) => entry.status)).toEqual([405, 405]);
231
+ expect(await bulkFoodNames()).toEqual([]);
232
+ });
233
+
234
+ it("reports 405, not a validation 400, for an unpermitted item with a bad body", async () => {
235
+ configureOpenApiValidator({});
236
+ mountFoodRouter({
237
+ bulk: true,
238
+ permissions: {...allPermissions, create: [Permissions.IsAdmin]},
239
+ } as Partial<RouterOptions>);
240
+ const agent = await authAsUser(app, "notAdmin");
241
+ const single = await agent.post("/food").send({calories: "lots", name: "bulk-a"});
242
+ expect(single.status).toBe(405);
243
+ const res = await agent
244
+ .post("/food/bulk")
245
+ .send({
246
+ atomic: false,
247
+ operations: [{body: {calories: "lots", name: "bulk-a"}, method: "create"}],
248
+ })
249
+ .expect(200);
250
+ expect(res.body.data[0].status).toBe(405);
251
+ });
252
+
253
+ it("allows an admin to create when create requires IsAdmin", async () => {
254
+ mountFoodRouter({
255
+ bulk: true,
256
+ permissions: {...allPermissions, create: [Permissions.IsAdmin]},
257
+ } as Partial<RouterOptions>);
258
+ const agent = await authAsUser(app, "admin");
259
+ const res = await agent
260
+ .post("/food/bulk")
261
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]})
262
+ .expect(200);
263
+ expect(res.body.data[0].status).toBe(201);
264
+ });
265
+
266
+ it("runs postCreate once per created doc in input order", async () => {
267
+ const seen: string[] = [];
268
+ mountFoodRouter({
269
+ bulk: true,
270
+ postCreate: (doc: Food) => {
271
+ seen.push(doc.name as string);
272
+ },
273
+ } as Partial<RouterOptions>);
274
+ const agent = await authAsUser(app, "notAdmin");
275
+ await agent
276
+ .post("/food/bulk")
277
+ .send({
278
+ atomic: false,
279
+ operations: [
280
+ {body: {name: "bulk-a"}, method: "create"},
281
+ {body: {name: "bulk-b"}, method: "create"},
282
+ {body: {name: "bulk-c"}, method: "create"},
283
+ ],
284
+ })
285
+ .expect(200);
286
+ expect(seen).toEqual(["bulk-a", "bulk-b", "bulk-c"]);
287
+ });
288
+
289
+ it("turns a throwing postCreate into a 400 post-create-hook-error and keeps the write", async () => {
290
+ const failing = {
291
+ bulk: true,
292
+ postCreate: (doc: Food) => {
293
+ if (doc.name === "bulk-b") {
294
+ throw new Error("boom");
295
+ }
296
+ },
297
+ } as Partial<RouterOptions>;
298
+ mountFoodRouter(failing);
299
+ const agent = await authAsUser(app, "notAdmin");
300
+ const res = await agent
301
+ .post("/food/bulk")
302
+ .send({
303
+ atomic: false,
304
+ operations: [
305
+ {body: {name: "bulk-a"}, method: "create"},
306
+ {body: {name: "bulk-b"}, method: "create"},
307
+ ],
308
+ })
309
+ .expect(200);
310
+ expect(res.body.data[0].status).toBe(201);
311
+ expect(res.body.data[1].status).toBe(400);
312
+ expect(res.body.data[1].error.code).toBe("post-create-hook-error");
313
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
314
+
315
+ const single = await agent.post("/food").send({name: "bulk-b"}).expect(400);
316
+ expect(res.body.data[1].error).toEqual(single.body);
317
+ });
318
+
319
+ it("matches the single route for a preCreate that throws a plain Error", async () => {
320
+ mountFoodRouter({
321
+ bulk: true,
322
+ preCreate: () => {
323
+ throw new Error("x");
324
+ },
325
+ } as Partial<RouterOptions>);
326
+ const agent = await authAsUser(app, "notAdmin");
327
+ const single = await agent.post("/food").send({name: "bulk-a"});
328
+ expect(single.status).toBe(400);
329
+ expect(single.body.code).toBe("pre-create-hook-error");
330
+ const res = await agent
331
+ .post("/food/bulk")
332
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]})
333
+ .expect(200);
334
+ expect(res.body.data[0].status).toBe(400);
335
+ expect(res.body.data[0].error).toEqual(single.body);
336
+ });
337
+
338
+ it("maps a non-APIError thrown past the executor to a 500 entry", async () => {
339
+ mountFoodRouter({
340
+ bulk: true,
341
+ responseHandler: () => {
342
+ throw new Error("serializer exploded");
343
+ },
344
+ } as Partial<RouterOptions>);
345
+ const agent = await authAsUser(app, "notAdmin");
346
+ const res = await agent
347
+ .post("/food/bulk")
348
+ .send({atomic: false, operations: [{body: {name: "bulk-a"}, method: "create"}]})
349
+ .expect(200);
350
+ expect(res.body.data[0].status).toBe(500);
351
+ expect(res.body.data[0].index).toBe(0);
352
+ // The create was written before responseHandler failed: its id is still reported.
353
+ const [created] = await FoodModel.find({name: "bulk-a"});
354
+ expect(res.body.data[0].id).toBe(created.id);
355
+ expect(typeof res.body.data[0].error.title).toBe("string");
356
+ });
357
+
358
+ it("reports a Mongoose ValidationError as 400 with meta.fields, matching POST /food", async () => {
359
+ mountFoodRouter({bulk: true} as Partial<RouterOptions>);
360
+ const agent = await authAsUser(app, "notAdmin");
361
+ const single = await agent
362
+ .post("/food")
363
+ .send({eatenBy: ["not-an-object-id"], name: "bulk-a"})
364
+ .expect(400);
365
+ const res = await agent
366
+ .post("/food/bulk")
367
+ .send({
368
+ atomic: false,
369
+ operations: [
370
+ {body: {name: "bulk-ok"}, method: "create"},
371
+ {body: {eatenBy: ["not-an-object-id"], name: "bulk-a"}, method: "create"},
372
+ ],
373
+ })
374
+ .expect(200);
375
+ expect(res.body.data[0].status).toBe(201);
376
+ expect(res.body.data[1].status).toBe(400);
377
+ expect(res.body.data[1].error.meta?.fields).toBeDefined();
378
+ expect(res.body.data[1].error).toEqual(single.body);
379
+ });
380
+
381
+ it("validates each create body when the OpenAPI validator is configured", async () => {
382
+ configureOpenApiValidator({});
383
+ mountFoodRouter({bulk: true} as Partial<RouterOptions>);
384
+ const agent = await authAsUser(app, "notAdmin");
385
+ // Test fix (Pick): Food's schema requires `likesIds`, so a valid body must send it.
386
+ const single = await agent
387
+ .post("/food")
388
+ .send({calories: "lots", likesIds: [], name: "bulk-a"});
389
+ expect(single.status).toBe(400);
390
+ const res = await agent
391
+ .post("/food/bulk")
392
+ .send({
393
+ atomic: false,
394
+ operations: [
395
+ {body: {calories: 3, likesIds: [], name: "bulk-ok"}, method: "create"},
396
+ {body: {calories: "lots", likesIds: [], name: "bulk-a"}, method: "create"},
397
+ ],
398
+ })
399
+ .expect(200);
400
+ expect(res.body.data[0].status).toBe(201);
401
+ expect(res.body.data[1].status).toBe(400);
402
+ expect(res.body.data[1].error).toEqual(single.body);
403
+ expect(await bulkFoodNames()).toEqual(["bulk-ok"]);
404
+ });
405
+ });
406
+
407
+ describe("envelope errors (whole-request 400, nothing written)", () => {
408
+ const post = async (
409
+ options: Partial<RouterOptions>,
410
+ payload: unknown
411
+ ): Promise<supertest.Response> => {
412
+ mountFoodRouter({bulk: true, ...options} as Partial<RouterOptions>);
413
+ const agent = await authAsUser(app, "notAdmin");
414
+ const res = await agent.post("/food/bulk").send(payload as object);
415
+ if (res.status === 400) {
416
+ expect(res.body.code).toBe("bulk-invalid-request");
417
+ }
418
+ return res;
419
+ };
420
+
421
+ const createItem = (name: string): {body: {name: string}; method: string} => ({
422
+ body: {name},
423
+ method: "create",
424
+ });
425
+
426
+ it("rejects a create item when bulk.methods excludes create", async () => {
427
+ const res = await post({bulk: {methods: ["update"]}} as Partial<RouterOptions>, {
428
+ atomic: false,
429
+ operations: [createItem("bulk-a")],
430
+ });
431
+ expect(res.status).toBe(400);
432
+ expect(await bulkFoodNames()).toEqual([]);
433
+ });
434
+
435
+ it("rejects more operations than bulk.maxItems", async () => {
436
+ const res = await post({bulk: {maxItems: 2}} as Partial<RouterOptions>, {
437
+ atomic: false,
438
+ operations: [createItem("bulk-a"), createItem("bulk-b"), createItem("bulk-c")],
439
+ });
440
+ expect(res.status).toBe(400);
441
+ expect(await bulkFoodNames()).toEqual([]);
442
+ });
443
+
444
+ it("accepts exactly bulk.maxItems operations", async () => {
445
+ const res = await post({bulk: {maxItems: 2}} as Partial<RouterOptions>, {
446
+ atomic: false,
447
+ operations: [createItem("bulk-a"), createItem("bulk-b")],
448
+ });
449
+ expect(res.status).toBe(200);
450
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
451
+ });
452
+
453
+ it("rejects more than 100 operations when bulk is true", async () => {
454
+ const operations = Array.from({length: 101}, (_, i) => createItem(`bulk-${i}`));
455
+ const res = await post({}, {atomic: false, operations});
456
+ expect(res.status).toBe(400);
457
+ expect(await FoodModel.countDocuments({name: /^bulk-/})).toBe(0);
458
+ });
459
+
460
+ it("rejects an empty operations array", async () => {
461
+ const res = await post({}, {atomic: false, operations: []});
462
+ expect(res.status).toBe(400);
463
+ });
464
+
465
+ it("rejects a missing operations key", async () => {
466
+ const res = await post({}, {atomic: false});
467
+ expect(res.status).toBe(400);
468
+ });
469
+
470
+ it("rejects a non-array operations value", async () => {
471
+ const res = await post({}, {atomic: false, operations: {method: "create"}});
472
+ expect(res.status).toBe(400);
473
+ });
474
+
475
+ it("rejects an unknown method", async () => {
476
+ const res = await post(
477
+ {},
478
+ {
479
+ atomic: false,
480
+ operations: [{body: {name: "bulk-a"}, method: "upsert"}],
481
+ }
482
+ );
483
+ expect(res.status).toBe(400);
484
+ expect(await bulkFoodNames()).toEqual([]);
485
+ });
486
+
487
+ it("rejects update and delete items without an id", async () => {
488
+ const update = await post(
489
+ {},
490
+ {
491
+ atomic: false,
492
+ operations: [{body: {name: "bulk-a"}, method: "update"}],
493
+ }
494
+ );
495
+ expect(update.status).toBe(400);
496
+ const remove = await supertest(app)
497
+ .post("/food/bulk")
498
+ .set("Authorization", `Bearer ${(await login()).token}`)
499
+ .send({atomic: false, operations: [{method: "delete"}]});
500
+ expect(remove.status).toBe(400);
501
+ });
502
+
503
+ it("rejects a create item without an object body", async () => {
504
+ const missing = await post({}, {atomic: false, operations: [{method: "create"}]});
505
+ expect(missing.status).toBe(400);
506
+ const notObject = await supertest(app)
507
+ .post("/food/bulk")
508
+ .set("Authorization", `Bearer ${(await login()).token}`)
509
+ .send({atomic: false, operations: [{body: "nope", method: "create"}]});
510
+ expect(notObject.status).toBe(400);
511
+ });
512
+
513
+ it("rejects a non-boolean atomic flag", async () => {
514
+ const res = await post({}, {atomic: "false", operations: [createItem("bulk-a")]});
515
+ expect(res.status).toBe(400);
516
+ expect(await bulkFoodNames()).toEqual([]);
517
+ });
518
+
519
+ it("does not write earlier valid items when a later item has an envelope error", async () => {
520
+ const res = await post(
521
+ {},
522
+ {
523
+ atomic: false,
524
+ operations: [createItem("bulk-a"), {body: {name: "bulk-b"}, method: "upsert"}],
525
+ }
526
+ );
527
+ expect(res.status).toBe(400);
528
+ expect(await bulkFoodNames()).toEqual([]);
529
+ });
530
+
531
+ const login = async (): Promise<{token: string}> => {
532
+ const res = await supertest(app)
533
+ .post("/auth/login")
534
+ .send({email: "notAdmin@example.com", password: "password"})
535
+ .expect(200);
536
+ return {token: res.body.data.token};
537
+ };
538
+ });
539
+
540
+ describe("audit", () => {
541
+ afterEach(() => {
542
+ resetAuditRecorderForTests();
543
+ if (mongoose.connection.models.TerrenoAuditEvent) {
544
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
545
+ }
546
+ });
547
+
548
+ it("writes one AuditEvent per created doc", async () => {
549
+ resetAuditRecorderForTests();
550
+ if (mongoose.connection.models.TerrenoAuditEvent) {
551
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
552
+ }
553
+ await mongoose.connection.collection("auditevents").deleteMany({});
554
+ const auditApp = new TerrenoApp({
555
+ skipListen: true,
556
+ userModel: UserModel as unknown as UserMongooseModel,
557
+ })
558
+ .register(new AuditApp())
559
+ .build();
560
+ auditApp.use(
561
+ "/food",
562
+ modelRouter(FoodModel, {
563
+ audit: true,
564
+ bulk: true,
565
+ permissions: allPermissions,
566
+ } as RouterOptions)
567
+ );
568
+ const agent = await authAsUser(auditApp, "notAdmin");
569
+ await agent
570
+ .post("/food/bulk")
571
+ .send({
572
+ atomic: false,
573
+ operations: [
574
+ {body: {name: "bulk-a"}, method: "create"},
575
+ {body: {name: "bulk-b"}, method: "create"},
576
+ ],
577
+ })
578
+ .expect(200);
579
+ await flushAuditRecorderForTests();
580
+ const adminAgent = await authAsUser(auditApp, "admin");
581
+ const list = await adminAgent.get("/audit-events?verb=created").expect(200);
582
+ expect(list.body.data).toHaveLength(2);
583
+ const labels = list.body.data.map((event: {after: {name: string}}) => event.after.name);
584
+ expect(labels.sort()).toEqual(["bulk-a", "bulk-b"]);
585
+ });
586
+ });
587
+ });
588
+
589
+ describe("validateModelRouterBody", () => {
590
+ beforeEach(() => {
591
+ configureOpenApiValidator({});
592
+ });
593
+
594
+ afterEach(() => {
595
+ resetOpenApiValidatorConfig();
596
+ });
597
+
598
+ it("returns the body for a valid create", () => {
599
+ // Test fix (Pick): Food's schema requires `likesIds`, so a valid body must send it.
600
+ const cleaned = validateModelRouterBody({
601
+ body: {calories: 3, likesIds: [], name: "bulk-a"},
602
+ method: "create",
603
+ model: FoodModel,
604
+ options: {permissions: allPermissions} as RouterOptions,
605
+ });
606
+ expect(cleaned.name).toBe("bulk-a");
607
+ expect(cleaned.calories).toBe(3);
608
+ });
609
+
610
+ it("throws a 400 APIError for a wrong-typed create field", () => {
611
+ let thrown: unknown;
612
+ try {
613
+ // Test fix (Pick): send the required `likesIds` so the 400 comes from `calories`.
614
+ validateModelRouterBody({
615
+ body: {calories: "lots", likesIds: [], name: "bulk-a"},
616
+ method: "create",
617
+ model: FoodModel,
618
+ options: {permissions: allPermissions} as RouterOptions,
619
+ });
620
+ } catch (error) {
621
+ thrown = error;
622
+ }
623
+ expect(isAPIError(thrown)).toBe(true);
624
+ expect((thrown as {status: number}).status).toBe(400);
625
+ expect(JSON.stringify((thrown as {meta?: unknown}).meta)).toContain("calories");
626
+ });
627
+
628
+ it("allows a partial body for update", () => {
629
+ const cleaned = validateModelRouterBody({
630
+ body: {calories: 9},
631
+ method: "update",
632
+ model: FoodModel,
633
+ options: {permissions: allPermissions} as RouterOptions,
634
+ });
635
+ expect(cleaned.calories).toBe(9);
636
+ });
637
+
638
+ it("returns the body unchanged when validation is disabled for the router", () => {
639
+ const body = {calories: "lots", name: "bulk-a"};
640
+ const cleaned = validateModelRouterBody({
641
+ body,
642
+ method: "create",
643
+ model: FoodModel,
644
+ options: {permissions: allPermissions, validation: false} as RouterOptions,
645
+ });
646
+ expect(cleaned).toEqual(body);
647
+ });
648
+ });
649
+
650
+ describe("toBulkItemError", () => {
651
+ it("maps a non-APIError to the fallthrough 500 body without leaking its message", () => {
652
+ const {body, status} = toBulkItemError(new Error("secret internal detail"));
653
+ expect(status).toBe(500);
654
+ expect(body).toEqual({status: 500, title: "Internal server error"});
655
+ });
656
+
657
+ it("maps a Mongoose CastError the way the error middleware does", () => {
658
+ const castError = new mongoose.Error.CastError("ObjectId", "nope", "eatenBy");
659
+ const {status} = toBulkItemError(castError);
660
+ expect(status).toBe(400);
661
+ });
662
+ });
663
+
664
+ interface BulkSoft extends IsDeleted {
665
+ _id: mongoose.Types.ObjectId;
666
+ calories?: number;
667
+ created: Date;
668
+ name: string;
669
+ ownerId?: mongoose.Types.ObjectId;
670
+ updated?: Date;
671
+ }
672
+
673
+ const bulkSoftSchema = new mongoose.Schema<BulkSoft>({
674
+ calories: {description: "Number of calories", type: Number},
675
+ name: {description: "The name of the item", required: true, type: String},
676
+ ownerId: {description: "The user who owns this item", ref: "User", type: "ObjectId"},
677
+ });
678
+ bulkSoftSchema.plugin(isDeletedPlugin);
679
+ bulkSoftSchema.plugin(createdUpdatedPlugin);
680
+ const BulkSoftModel = mongoose.model<BulkSoft>("BulkSoft", bulkSoftSchema);
681
+
682
+ interface BulkSynced extends IsDeleted {
683
+ _id: string;
684
+ _syncSeq?: number;
685
+ name: string;
686
+ ownerId: string;
687
+ }
688
+
689
+ const bulkSyncedSchema = new mongoose.Schema<BulkSynced>({
690
+ _id: {
691
+ default: (): string => new mongoose.Types.ObjectId().toHexString(),
692
+ description: "String id so the doc can be synced",
693
+ type: String,
694
+ },
695
+ name: {description: "The name of the item", required: true, type: String},
696
+ ownerId: {description: "The user who owns this item", required: true, type: String},
697
+ });
698
+ bulkSyncedSchema.plugin(isDeletedPlugin);
699
+ bulkSyncedSchema.plugin(createdUpdatedPlugin);
700
+ bulkSyncedSchema.plugin(syncPlugin);
701
+ const BulkSyncedModel = mongoose.model<BulkSynced>("BulkSynced", bulkSyncedSchema);
702
+
703
+ interface BulkEntry {
704
+ data?: Record<string, unknown>;
705
+ error?: Record<string, unknown>;
706
+ id?: string;
707
+ index: number;
708
+ method: string;
709
+ status: number;
710
+ }
711
+
712
+ describe("partial-mode update and delete", () => {
713
+ let app: express.Application;
714
+
715
+ const mountRouter = (
716
+ path: string,
717
+ model: mongoose.Model<never>,
718
+ options: Record<string, unknown>
719
+ ): void => {
720
+ app.use(
721
+ path,
722
+ modelRouter(model, {
723
+ bulk: true,
724
+ permissions: allPermissions,
725
+ ...options,
726
+ } as never)
727
+ );
728
+ app.use(apiUnauthorizedMiddleware);
729
+ app.use((_req: express.Request, res: express.Response) => {
730
+ res.status(404).json({title: "Not Found"});
731
+ });
732
+ };
733
+
734
+ const mountFood = (options: Partial<RouterOptions> = {}): void => {
735
+ mountRouter("/food", FoodModel as never, options as Record<string, unknown>);
736
+ };
737
+
738
+ const userId = async (email: string): Promise<mongoose.Types.ObjectId> => {
739
+ const user = await UserModel.findOne({email});
740
+ return (user as unknown as {_id: mongoose.Types.ObjectId})._id;
741
+ };
742
+
743
+ const bulk = async (
744
+ agent: TestAgent,
745
+ path: string,
746
+ operations: unknown[]
747
+ ): Promise<BulkEntry[]> => {
748
+ const res = await agent.post(`${path}/bulk`).send({atomic: false, operations}).expect(200);
749
+ return res.body.data as BulkEntry[];
750
+ };
751
+
752
+ const makeFood = async (
753
+ fields: Partial<Food> & {created?: Date} = {}
754
+ ): Promise<mongoose.HydratedDocument<Food>> =>
755
+ FoodModel.create({calories: 1, likesIds: [], name: "bulk-old", ...fields} as never);
756
+
757
+ beforeEach(async () => {
758
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
759
+ await setupDb();
760
+ await Promise.all([
761
+ FoodModel.deleteMany({}),
762
+ BulkSoftModel.deleteMany({}),
763
+ BulkSyncedModel.deleteMany({}),
764
+ ]);
765
+ clearSyncRegistry();
766
+ app = getBaseServer();
767
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
768
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
769
+ });
770
+
771
+ afterEach(() => {
772
+ resetOpenApiValidatorConfig();
773
+ clearSyncRegistry();
774
+ });
775
+
776
+ describe("update", () => {
777
+ it("updates two docs, runs preUpdate/postUpdate per item, and passes prevValue", async () => {
778
+ const preCalls: string[] = [];
779
+ const postCalls: {calories: number | undefined; prevCalories: number | undefined}[] = [];
780
+ mountFood({
781
+ postUpdate: (doc: Food, _body: Partial<Food>, _req: express.Request, prev: Food) => {
782
+ postCalls.push({calories: doc.calories, prevCalories: prev.calories});
783
+ },
784
+ preUpdate: (body: Partial<Food>) => {
785
+ preCalls.push(String(body.calories));
786
+ return body as Food;
787
+ },
788
+ } as Partial<RouterOptions>);
789
+ const agent = await authAsUser(app, "notAdmin");
790
+ const owner = await userId("notAdmin@example.com");
791
+ const a = await makeFood({calories: 1, name: "bulk-a", ownerId: owner} as never);
792
+ const b = await makeFood({calories: 2, name: "bulk-b", ownerId: owner} as never);
793
+
794
+ const entries = await bulk(agent, "/food", [
795
+ {body: {calories: 10}, id: a.id, method: "update"},
796
+ {body: {calories: 20}, id: b.id, method: "update"},
797
+ ]);
798
+
799
+ expect(entries.map((entry) => entry.status)).toEqual([200, 200]);
800
+ expect(entries.map((entry) => entry.index)).toEqual([0, 1]);
801
+ expect(entries.map((entry) => entry.id)).toEqual([a.id, b.id]);
802
+ expect(entries.map((entry) => entry.method)).toEqual(["update", "update"]);
803
+ expect((await FoodModel.findById(a.id))?.calories).toBe(10);
804
+ expect((await FoodModel.findById(b.id))?.calories).toBe(20);
805
+ expect(preCalls).toEqual(["10", "20"]);
806
+ expect(postCalls).toEqual([
807
+ {calories: 10, prevCalories: 1},
808
+ {calories: 20, prevCalories: 2},
809
+ ]);
810
+ });
811
+
812
+ it("returns the same data a PATCH /food/:id returns for the same body", async () => {
813
+ mountFood();
814
+ const agent = await authAsUser(app, "notAdmin");
815
+ const owner = await userId("notAdmin@example.com");
816
+ const doc = await makeFood({name: "bulk-a", ownerId: owner} as never);
817
+ const entries = await bulk(agent, "/food", [
818
+ {body: {calories: 77}, id: doc.id, method: "update"},
819
+ ]);
820
+ const single = await agent.patch(`/food/${doc.id}`).send({calories: 77}).expect(200);
821
+ expect(entries[0].status).toBe(200);
822
+ expect(stripVolatile(entries[0].data as Record<string, unknown>)).toEqual(
823
+ stripVolatile(single.body.data)
824
+ );
825
+ });
826
+
827
+ it("reports 403 for an item targeting another user's doc and 200 for the owner's", async () => {
828
+ mountFood({
829
+ permissions: {...allPermissions, update: [Permissions.IsOwner]},
830
+ } as Partial<RouterOptions>);
831
+ const agent = await authAsUser(app, "notAdmin");
832
+ const mine = await makeFood({
833
+ calories: 1,
834
+ name: "bulk-mine",
835
+ ownerId: await userId("notAdmin@example.com"),
836
+ } as never);
837
+ const theirs = await makeFood({
838
+ calories: 1,
839
+ name: "bulk-theirs",
840
+ ownerId: await userId("admin@example.com"),
841
+ } as never);
842
+ const entries = await bulk(agent, "/food", [
843
+ {body: {calories: 5}, id: theirs.id, method: "update"},
844
+ {body: {calories: 5}, id: mine.id, method: "update"},
845
+ ]);
846
+ expect(entries.map((entry) => entry.status)).toEqual([403, 200]);
847
+ expect((await FoodModel.findById(theirs.id))?.calories).toBe(1);
848
+ expect((await FoodModel.findById(mine.id))?.calories).toBe(5);
849
+ });
850
+
851
+ it("reports 404 for a nonexistent id", async () => {
852
+ mountFood();
853
+ const agent = await authAsUser(app, "notAdmin");
854
+ const missing = new mongoose.Types.ObjectId().toString();
855
+ const single = await agent.patch(`/food/${missing}`).send({calories: 1});
856
+ expect(single.status).toBe(404);
857
+ const entries = await bulk(agent, "/food", [
858
+ {body: {calories: 1}, id: missing, method: "update"},
859
+ ]);
860
+ expect(entries[0].status).toBe(404);
861
+ expect(entries[0].index).toBe(0);
862
+ });
863
+
864
+ it("reports the same status as PATCH for a malformed id", async () => {
865
+ mountFood();
866
+ const agent = await authAsUser(app, "notAdmin");
867
+ const single = await agent.patch("/food/not-an-object-id").send({calories: 1});
868
+ const entries = await bulk(agent, "/food", [
869
+ {body: {calories: 1}, id: "not-an-object-id", method: "update"},
870
+ ]);
871
+ expect(entries[0].status).toBe(single.status);
872
+ });
873
+
874
+ it("reports 405, not 404, for a nonexistent id when update permission is []", async () => {
875
+ mountFood({permissions: {...allPermissions, update: []}} as Partial<RouterOptions>);
876
+ const agent = await authAsUser(app, "notAdmin");
877
+ const missing = new mongoose.Types.ObjectId().toString();
878
+ const single = await agent.patch(`/food/${missing}`).send({calories: 1});
879
+ expect(single.status).toBe(405);
880
+ const entries = await bulk(agent, "/food", [
881
+ {body: {calories: 1}, id: missing, method: "update"},
882
+ ]);
883
+ expect(entries[0].status).toBe(405);
884
+ });
885
+
886
+ it("reports 409 with the PATCH conflict body for a stale _updatedAt, and 200 for a newer one", async () => {
887
+ mountFood();
888
+ const agent = await authAsUser(app, "notAdmin");
889
+ const owner = await userId("notAdmin@example.com");
890
+ const created = DateTime.fromISO("2024-06-01T12:00:00.000Z").toJSDate();
891
+ const doc = await makeFood({calories: 1, created, name: "bulk-a", ownerId: owner} as never);
892
+ const stale = "2024-01-01T00:00:00.000Z";
893
+ const newer = "2025-01-01T00:00:00.000Z";
894
+
895
+ const single = await agent
896
+ .patch(`/food/${doc.id}`)
897
+ .send({_updatedAt: stale, calories: 2})
898
+ .expect(409);
899
+ const entries = await bulk(agent, "/food", [
900
+ {body: {_updatedAt: stale, calories: 2}, id: doc.id, method: "update"},
901
+ {body: {_updatedAt: newer, calories: 3}, id: doc.id, method: "update"},
902
+ ]);
903
+
904
+ expect(entries[0].status).toBe(409);
905
+ expect(entries[0].error).toEqual(single.body);
906
+ expect(entries[0].error?.error).toBe("Conflict");
907
+ expect(entries[0].error?.message).toBe("Document was modified since your last read");
908
+ expect(entries[1].status).toBe(200);
909
+ expect((await FoodModel.findById(doc.id))?.calories).toBe(3);
910
+ });
911
+
912
+ it("reports 400 for an unparseable _updatedAt, matching PATCH", async () => {
913
+ mountFood();
914
+ const agent = await authAsUser(app, "notAdmin");
915
+ const owner = await userId("notAdmin@example.com");
916
+ const doc = await makeFood({name: "bulk-a", ownerId: owner} as never);
917
+ const single = await agent
918
+ .patch(`/food/${doc.id}`)
919
+ .send({_updatedAt: "not-a-date", calories: 2});
920
+ expect(single.status).toBe(400);
921
+ const entries = await bulk(agent, "/food", [
922
+ {body: {_updatedAt: "not-a-date", calories: 2}, id: doc.id, method: "update"},
923
+ ]);
924
+ expect(entries[0].status).toBe(400);
925
+ expect(entries[0].error).toEqual(single.body);
926
+ });
927
+
928
+ it("reports 400 with the PATCH body for a wrong-typed field when validation is on", async () => {
929
+ configureOpenApiValidator({});
930
+ mountFood();
931
+ const agent = await authAsUser(app, "notAdmin");
932
+ const owner = await userId("notAdmin@example.com");
933
+ const doc = await makeFood({calories: 1, name: "bulk-a", ownerId: owner} as never);
934
+ const single = await agent.patch(`/food/${doc.id}`).send({calories: "lots"});
935
+ expect(single.status).toBe(400);
936
+ const entries = await bulk(agent, "/food", [
937
+ {body: {calories: "lots"}, id: doc.id, method: "update"},
938
+ {body: {calories: 9}, id: doc.id, method: "update"},
939
+ ]);
940
+ expect(entries[0].status).toBe(400);
941
+ expect(entries[0].error).toEqual(single.body);
942
+ expect(entries[1].status).toBe(200);
943
+ expect((await FoodModel.findById(doc.id))?.calories).toBe(9);
944
+ });
945
+
946
+ it("strips deleted:true from an update body on a soft-delete model, as PATCH does", async () => {
947
+ mountRouter("/soft", BulkSoftModel as never, {});
948
+ const agent = await authAsUser(app, "notAdmin");
949
+ const viaPatch = await BulkSoftModel.create({name: "bulk-patch"});
950
+ const viaBulk = await BulkSoftModel.create({name: "bulk-bulk"});
951
+ await agent.patch(`/soft/${viaPatch.id}`).send({deleted: true, name: "bulk-patched"});
952
+ const entries = await bulk(agent, "/soft", [
953
+ {body: {deleted: true, name: "bulk-bulked"}, id: viaBulk.id, method: "update"},
954
+ ]);
955
+ expect(entries[0].status).toBe(200);
956
+ const patched = await BulkSoftModel.findById(viaPatch.id);
957
+ const bulked = await BulkSoftModel.findById(viaBulk.id);
958
+ expect(patched?.deleted).not.toBe(true);
959
+ expect(bulked?.deleted).not.toBe(true);
960
+ expect(bulked?.name).toBe("bulk-bulked");
961
+ });
962
+
963
+ it("applies repeated updates to the same id in input order", async () => {
964
+ mountFood();
965
+ const agent = await authAsUser(app, "notAdmin");
966
+ const owner = await userId("notAdmin@example.com");
967
+ const doc = await makeFood({calories: 1, name: "bulk-a", ownerId: owner} as never);
968
+ const entries = await bulk(agent, "/food", [
969
+ {body: {calories: 2}, id: doc.id, method: "update"},
970
+ {body: {calories: 3}, id: doc.id, method: "update"},
971
+ ]);
972
+ expect(entries.map((entry) => entry.status)).toEqual([200, 200]);
973
+ expect((await FoodModel.findById(doc.id))?.calories).toBe(3);
974
+ });
975
+
976
+ it("turns a throwing postUpdate into a 400 post-update-hook-error and keeps the write", async () => {
977
+ mountFood({
978
+ postUpdate: () => {
979
+ throw new Error("boom");
980
+ },
981
+ } as Partial<RouterOptions>);
982
+ const agent = await authAsUser(app, "notAdmin");
983
+ const owner = await userId("notAdmin@example.com");
984
+ const doc = await makeFood({calories: 1, name: "bulk-a", ownerId: owner} as never);
985
+ const entries = await bulk(agent, "/food", [
986
+ {body: {calories: 8}, id: doc.id, method: "update"},
987
+ ]);
988
+ expect(entries[0].status).toBe(400);
989
+ expect(entries[0].error?.code).toBe("post-update-hook-error");
990
+ expect((await FoodModel.findById(doc.id))?.calories).toBe(8);
991
+ });
992
+
993
+ it("reports 403 'Update not allowed' for an item whose preUpdate returns null", async () => {
994
+ mountFood({
995
+ preUpdate: (body: Partial<Food>) => (body.calories === 99 ? null : (body as Food)),
996
+ } as Partial<RouterOptions>);
997
+ const agent = await authAsUser(app, "notAdmin");
998
+ const owner = await userId("notAdmin@example.com");
999
+ const doc = await makeFood({calories: 1, name: "bulk-a", ownerId: owner} as never);
1000
+ const entries = await bulk(agent, "/food", [
1001
+ {body: {calories: 99}, id: doc.id, method: "update"},
1002
+ {body: {calories: 5}, id: doc.id, method: "update"},
1003
+ ]);
1004
+ expect(entries.map((entry) => entry.status)).toEqual([403, 200]);
1005
+ expect((await FoodModel.findById(doc.id))?.calories).toBe(5);
1006
+ });
1007
+ });
1008
+
1009
+ describe("delete", () => {
1010
+ it("soft deletes two docs, returns 204 entries with no data, and runs delete hooks per item", async () => {
1011
+ const preCalls: string[] = [];
1012
+ const postCalls: string[] = [];
1013
+ mountRouter("/soft", BulkSoftModel as never, {
1014
+ postDelete: (_req: express.Request, doc: BulkSoft) => {
1015
+ postCalls.push(doc.name);
1016
+ },
1017
+ preDelete: (doc: BulkSoft) => {
1018
+ preCalls.push(doc.name);
1019
+ return doc;
1020
+ },
1021
+ });
1022
+ const agent = await authAsUser(app, "notAdmin");
1023
+ const a = await BulkSoftModel.create({name: "bulk-a"});
1024
+ const b = await BulkSoftModel.create({name: "bulk-b"});
1025
+ const entries = await bulk(agent, "/soft", [
1026
+ {id: a.id, method: "delete"},
1027
+ {id: b.id, method: "delete"},
1028
+ ]);
1029
+ expect(entries.map((entry) => entry.status)).toEqual([204, 204]);
1030
+ expect(entries.map((entry) => entry.id)).toEqual([a.id, b.id]);
1031
+ expect(entries.map((entry) => entry.index)).toEqual([0, 1]);
1032
+ expect(entries[0].data).toBeUndefined();
1033
+ expect(entries[0].error).toBeUndefined();
1034
+ expect((await BulkSoftModel.findOne({_id: a.id, deleted: true}))?.deleted).toBe(true);
1035
+ expect(await BulkSoftModel.countDocuments({deleted: true})).toBe(2);
1036
+ expect(preCalls).toEqual(["bulk-a", "bulk-b"]);
1037
+ expect(postCalls).toEqual(["bulk-a", "bulk-b"]);
1038
+ });
1039
+
1040
+ it("reports an already soft-deleted doc as the 404 DELETE /:id returns, without rerunning postDelete", async () => {
1041
+ const postCalls: string[] = [];
1042
+ mountRouter("/soft", BulkSoftModel as never, {
1043
+ postDelete: (_req: express.Request, doc: BulkSoft) => {
1044
+ postCalls.push(doc.name);
1045
+ },
1046
+ });
1047
+ const agent = await authAsUser(app, "notAdmin");
1048
+ const a = await BulkSoftModel.create({name: "bulk-a"});
1049
+ const gone = await BulkSoftModel.create({name: "bulk-gone"});
1050
+ await agent.delete(`/soft/${gone.id}`).expect(204);
1051
+ const single = await agent.delete(`/soft/${gone.id}`);
1052
+ expect(single.status).toBe(404);
1053
+ postCalls.length = 0;
1054
+
1055
+ const entries = await bulk(agent, "/soft", [
1056
+ {id: a.id, method: "delete"},
1057
+ {id: a.id, method: "delete"},
1058
+ {id: gone.id, method: "delete"},
1059
+ ]);
1060
+ expect(entries.map((entry) => entry.status)).toEqual([204, 404, 404]);
1061
+ expect(entries[2].error).toEqual(single.body);
1062
+ expect(postCalls).toEqual(["bulk-a"]);
1063
+ });
1064
+
1065
+ it("reports 405 for every item when delete permission is []", async () => {
1066
+ mountRouter("/soft", BulkSoftModel as never, {
1067
+ permissions: {...allPermissions, delete: []},
1068
+ });
1069
+ const agent = await authAsUser(app, "notAdmin");
1070
+ const a = await BulkSoftModel.create({name: "bulk-a"});
1071
+ const entries = await bulk(agent, "/soft", [{id: a.id, method: "delete"}]);
1072
+ expect(entries[0].status).toBe(405);
1073
+ expect(await BulkSoftModel.countDocuments({deleted: true})).toBe(0);
1074
+ });
1075
+
1076
+ it("reports 403 for another user's doc under IsOwner and 204 for the owner's", async () => {
1077
+ mountRouter("/soft", BulkSoftModel as never, {
1078
+ permissions: {...allPermissions, delete: [Permissions.IsOwner]},
1079
+ });
1080
+ const agent = await authAsUser(app, "notAdmin");
1081
+ const mine = await BulkSoftModel.create({
1082
+ name: "bulk-mine",
1083
+ ownerId: await userId("notAdmin@example.com"),
1084
+ });
1085
+ const theirs = await BulkSoftModel.create({
1086
+ name: "bulk-theirs",
1087
+ ownerId: await userId("admin@example.com"),
1088
+ });
1089
+ const entries = await bulk(agent, "/soft", [
1090
+ {id: theirs.id, method: "delete"},
1091
+ {id: mine.id, method: "delete"},
1092
+ ]);
1093
+ expect(entries.map((entry) => entry.status)).toEqual([403, 204]);
1094
+ expect(await BulkSoftModel.countDocuments({deleted: true})).toBe(1);
1095
+ });
1096
+
1097
+ it("reports 404 for a nonexistent id, matching DELETE", async () => {
1098
+ mountRouter("/soft", BulkSoftModel as never, {});
1099
+ const agent = await authAsUser(app, "notAdmin");
1100
+ const missing = new mongoose.Types.ObjectId().toString();
1101
+ const single = await agent.delete(`/soft/${missing}`);
1102
+ expect(single.status).toBe(404);
1103
+ const entries = await bulk(agent, "/soft", [{id: missing, method: "delete"}]);
1104
+ expect(entries[0].status).toBe(404);
1105
+ });
1106
+
1107
+ it("reports 403 'Delete not allowed' for an item whose preDelete returns null", async () => {
1108
+ mountRouter("/soft", BulkSoftModel as never, {
1109
+ preDelete: (doc: BulkSoft) => (doc.name === "bulk-keep" ? null : doc),
1110
+ });
1111
+ const agent = await authAsUser(app, "notAdmin");
1112
+ const keep = await BulkSoftModel.create({name: "bulk-keep"});
1113
+ const drop = await BulkSoftModel.create({name: "bulk-drop"});
1114
+ const entries = await bulk(agent, "/soft", [
1115
+ {id: keep.id, method: "delete"},
1116
+ {id: drop.id, method: "delete"},
1117
+ ]);
1118
+ expect(entries.map((entry) => entry.status)).toEqual([403, 204]);
1119
+ expect(await BulkSoftModel.countDocuments({deleted: true})).toBe(1);
1120
+ });
1121
+
1122
+ it("hard deletes on a model without soft delete", async () => {
1123
+ mountFood();
1124
+ const agent = await authAsUser(app, "notAdmin");
1125
+ const doc = await makeFood({name: "bulk-a"});
1126
+ const entries = await bulk(agent, "/food", [{id: doc.id, method: "delete"}]);
1127
+ expect(entries[0].status).toBe(204);
1128
+ expect(await FoodModel.findById(doc.id)).toBeNull();
1129
+ });
1130
+ });
1131
+
1132
+ describe("mixed", () => {
1133
+ it("runs create, update, and delete in one request and returns 201/200/204 in order", async () => {
1134
+ mountRouter("/soft", BulkSoftModel as never, {});
1135
+ const agent = await authAsUser(app, "notAdmin");
1136
+ const toUpdate = await BulkSoftModel.create({name: "bulk-old"});
1137
+ const toDelete = await BulkSoftModel.create({name: "bulk-gone"});
1138
+ const entries = await bulk(agent, "/soft", [
1139
+ {body: {name: "bulk-new"}, method: "create"},
1140
+ {body: {name: "bulk-updated"}, id: toUpdate.id, method: "update"},
1141
+ {id: toDelete.id, method: "delete"},
1142
+ ]);
1143
+ expect(entries.map((entry) => entry.status)).toEqual([201, 200, 204]);
1144
+ expect(entries.map((entry) => entry.method)).toEqual(["create", "update", "delete"]);
1145
+ expect(entries.map((entry) => entry.index)).toEqual([0, 1, 2]);
1146
+ expect((await BulkSoftModel.findById(toUpdate.id))?.name).toBe("bulk-updated");
1147
+ expect(await BulkSoftModel.countDocuments({name: "bulk-new"})).toBe(1);
1148
+ expect(await BulkSoftModel.countDocuments({deleted: true})).toBe(1);
1149
+ });
1150
+
1151
+ it("an update then a delete of the same id both succeed in input order", async () => {
1152
+ mountRouter("/soft", BulkSoftModel as never, {});
1153
+ const agent = await authAsUser(app, "notAdmin");
1154
+ const doc = await BulkSoftModel.create({name: "bulk-a"});
1155
+ const entries = await bulk(agent, "/soft", [
1156
+ {body: {name: "bulk-b"}, id: doc.id, method: "update"},
1157
+ {id: doc.id, method: "delete"},
1158
+ ]);
1159
+ expect(entries.map((entry) => entry.status)).toEqual([200, 204]);
1160
+ });
1161
+ });
1162
+
1163
+ describe("audit", () => {
1164
+ it("writes one AuditEvent per update and delete item with before/after", async () => {
1165
+ resetAuditRecorderForTests();
1166
+ if (mongoose.connection.models.TerrenoAuditEvent) {
1167
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
1168
+ }
1169
+ await mongoose.connection.collection("auditevents").deleteMany({});
1170
+ const auditApp = new TerrenoApp({
1171
+ skipListen: true,
1172
+ userModel: UserModel as unknown as UserMongooseModel,
1173
+ })
1174
+ .register(new AuditApp())
1175
+ .build();
1176
+ auditApp.use(
1177
+ "/soft",
1178
+ modelRouter(
1179
+ BulkSoftModel as never,
1180
+ {
1181
+ audit: true,
1182
+ bulk: true,
1183
+ permissions: allPermissions,
1184
+ } as never
1185
+ )
1186
+ );
1187
+ const agent = await authAsUser(auditApp, "notAdmin");
1188
+ const toUpdate = await BulkSoftModel.create({name: "audit-old"});
1189
+ const toDelete = await BulkSoftModel.create({name: "audit-gone"});
1190
+ await agent
1191
+ .post("/soft/bulk")
1192
+ .send({
1193
+ atomic: false,
1194
+ operations: [
1195
+ {body: {name: "audit-new"}, id: toUpdate.id, method: "update"},
1196
+ {id: toDelete.id, method: "delete"},
1197
+ ],
1198
+ })
1199
+ .expect(200);
1200
+ await flushAuditRecorderForTests();
1201
+ const adminAgent = await authAsUser(auditApp, "admin");
1202
+ const list = await adminAgent.get("/audit-events").expect(200);
1203
+ const events = list.body.data as {
1204
+ after?: {name?: string};
1205
+ before?: {name?: string};
1206
+ operation: string;
1207
+ recordId: string;
1208
+ }[];
1209
+ const updated = events.filter((event) => event.operation === "update");
1210
+ const deleted = events.filter((event) => event.operation === "delete");
1211
+ expect(updated).toHaveLength(1);
1212
+ expect(deleted).toHaveLength(1);
1213
+ expect(updated[0].recordId).toBe(toUpdate.id);
1214
+ expect(updated[0].before?.name).toBe("audit-old");
1215
+ expect(updated[0].after?.name).toBe("audit-new");
1216
+ expect(deleted[0].recordId).toBe(toDelete.id);
1217
+ expect(deleted[0].before?.name).toBe("audit-gone");
1218
+
1219
+ resetAuditRecorderForTests();
1220
+ if (mongoose.connection.models.TerrenoAuditEvent) {
1221
+ mongoose.connection.deleteModel("TerrenoAuditEvent");
1222
+ }
1223
+ });
1224
+ });
1225
+
1226
+ describe("synced model", () => {
1227
+ it("advances _syncSeq on a bulk update and soft-deletes on a bulk delete", async () => {
1228
+ const options = {permissions: allPermissions, sync: {scope: {type: "owner"}}};
1229
+ registerSync({
1230
+ config: {scope: {type: "owner"}},
1231
+ model: BulkSyncedModel as never,
1232
+ options: options as never,
1233
+ routePath: "/synced",
1234
+ });
1235
+ mountRouter("/synced", BulkSyncedModel as never, options);
1236
+ const agent = await authAsUser(app, "notAdmin");
1237
+ const owner = (await userId("notAdmin@example.com")).toString();
1238
+ const doc = await BulkSyncedModel.create({name: "bulk-a", ownerId: owner});
1239
+ const before = (await BulkSyncedModel.findById(doc.id))?._syncSeq;
1240
+ expect(typeof before).toBe("number");
1241
+
1242
+ const entries = await bulk(agent, "/synced", [
1243
+ {body: {name: "bulk-b"}, id: doc.id, method: "update"},
1244
+ ]);
1245
+ expect(entries[0].status).toBe(200);
1246
+ const afterUpdate = (await BulkSyncedModel.findById(doc.id))?._syncSeq as number;
1247
+ expect(afterUpdate).toBeGreaterThan(before as number);
1248
+
1249
+ const deletes = await bulk(agent, "/synced", [{id: doc.id, method: "delete"}]);
1250
+ expect(deletes[0].status).toBe(204);
1251
+ const tombstone = await BulkSyncedModel.findOne({_id: doc.id, deleted: true});
1252
+ expect(tombstone?.deleted).toBe(true);
1253
+ expect(tombstone?._syncSeq as number).toBeGreaterThan(afterUpdate);
1254
+ });
1255
+ });
1256
+ });