@terreno/api 0.29.0 → 0.31.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 (79) hide show
  1. package/CHANGELOG.md +2 -43
  2. package/LICENSE +21 -202
  3. package/dist/actions.js +17 -8
  4. package/dist/actions.openApi.test.js +1 -3
  5. package/dist/actions.test.js +8 -5
  6. package/dist/api.arrayOperations.test.js +16 -8
  7. package/dist/api.coverage.test.js +2 -3
  8. package/dist/api.d.ts +3 -2
  9. package/dist/api.errorPaths.test.js +608 -1
  10. package/dist/api.errors.test.js +9 -0
  11. package/dist/api.js +137 -170
  12. package/dist/api.query.test.js +20 -8
  13. package/dist/api.test.js +12 -6
  14. package/dist/auth.coverage.test.d.ts +1 -0
  15. package/dist/auth.coverage.test.js +202 -0
  16. package/dist/auth.test.js +159 -0
  17. package/dist/betterAuthSetup.d.ts +15 -1
  18. package/dist/betterAuthSetup.js +4 -6
  19. package/dist/configurationPlugin.js +2 -2
  20. package/dist/consentApp.test.js +1 -5
  21. package/dist/docLoader.js +5 -1
  22. package/dist/envConfigurationPlugin.d.ts +1 -1
  23. package/dist/envConfigurationPlugin.js +0 -2
  24. package/dist/errors.d.ts +14 -0
  25. package/dist/errors.js +24 -2
  26. package/dist/errors.test.js +137 -0
  27. package/dist/expressServer.js +11 -5
  28. package/dist/githubAuth.js +1 -4
  29. package/dist/httpClient.js +5 -1
  30. package/dist/openApiBuilder.test.js +0 -2
  31. package/dist/openApiValidator.test.js +34 -0
  32. package/dist/plugins.d.ts +6 -5
  33. package/dist/plugins.js +56 -10
  34. package/dist/plugins.test.js +73 -17
  35. package/dist/populate.test.js +9 -12
  36. package/dist/realtime/realtime.test.js +231 -0
  37. package/dist/realtime/realtimeApp.d.ts +1 -1
  38. package/dist/realtime/realtimeApp.js +6 -2
  39. package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
  40. package/dist/realtime/realtimeAppSetup.test.js +213 -0
  41. package/dist/realtime/registry.d.ts +3 -2
  42. package/dist/tests/models.d.ts +27 -11
  43. package/dist/tests/models.js +5 -3
  44. package/dist/tests/testHelper.d.ts +9 -3
  45. package/package.json +4 -5
  46. package/src/actions.openApi.test.ts +7 -10
  47. package/src/actions.test.ts +27 -15
  48. package/src/actions.ts +21 -12
  49. package/src/api.arrayOperations.test.ts +16 -8
  50. package/src/api.coverage.test.ts +9 -10
  51. package/src/api.errorPaths.test.ts +360 -4
  52. package/src/api.errors.test.ts +12 -0
  53. package/src/api.query.test.ts +20 -8
  54. package/src/api.test.ts +12 -6
  55. package/src/api.ts +162 -171
  56. package/src/auth.coverage.test.ts +101 -0
  57. package/src/auth.test.ts +125 -2
  58. package/src/betterAuthSetup.ts +7 -7
  59. package/src/configurationPlugin.ts +2 -2
  60. package/src/consentApp.test.ts +12 -12
  61. package/src/docLoader.ts +6 -2
  62. package/src/envConfigurationPlugin.ts +2 -6
  63. package/src/errors.test.ts +106 -1
  64. package/src/errors.ts +25 -1
  65. package/src/expressServer.ts +11 -5
  66. package/src/githubAuth.ts +1 -3
  67. package/src/httpClient.ts +6 -2
  68. package/src/models/versionConfig.ts +1 -1
  69. package/src/openApiBuilder.test.ts +24 -9
  70. package/src/openApiValidator.test.ts +41 -0
  71. package/src/plugins.test.ts +59 -9
  72. package/src/plugins.ts +81 -39
  73. package/src/populate.test.ts +25 -16
  74. package/src/realtime/changeStreamWatcher.ts +8 -1
  75. package/src/realtime/realtime.test.ts +239 -0
  76. package/src/realtime/realtimeApp.ts +8 -5
  77. package/src/realtime/realtimeAppSetup.test.ts +161 -0
  78. package/src/realtime/registry.ts +3 -4
  79. package/src/tests/models.ts +8 -6
@@ -83,7 +83,8 @@ describe("model array operations", () => {
83
83
  .post(`/food/${apple._id}/categories`)
84
84
  .send({name: "Good Seller", show: false})
85
85
  .expect(400);
86
- expect(res.body.title).toBe(
86
+ expect(res.body.title).toBe("Malformed array operation body");
87
+ expect(res.body.detail).toBe(
87
88
  "Malformed body, array operations should have a single, top level key, got: name,show"
88
89
  );
89
90
 
@@ -106,7 +107,8 @@ describe("model array operations", () => {
106
107
  .patch(`/food/${apple._id}/categories/xyz`)
107
108
  .send({categories: {name: "Good Seller", show: false}})
108
109
  .expect(404);
109
- expect(res.body.title).toBe("Could not find categories/xyz");
110
+ expect(res.body.title).toBe("Array item not found");
111
+ expect(res.body.detail).toBe("Could not find categories/xyz");
110
112
  res = await agent
111
113
  .patch(`/food/${apple._id}/categories/${apple.categories[1]._id}`)
112
114
  .send({categories: {name: "Good Seller", show: false}})
@@ -117,7 +119,8 @@ describe("model array operations", () => {
117
119
 
118
120
  it("delete array sub-schema item", async () => {
119
121
  let res = await agent.delete(`/food/${apple._id}/categories/xyz`).expect(404);
120
- expect(res.body.title).toBe("Could not find categories/xyz");
122
+ expect(res.body.title).toBe("Array item not found");
123
+ expect(res.body.detail).toBe("Could not find categories/xyz");
121
124
  res = await agent
122
125
  .delete(`/food/${apple._id}/categories/${apple.categories[0]._id}`)
123
126
  .expect(200);
@@ -139,7 +142,8 @@ describe("model array operations", () => {
139
142
  .patch(`/food/${apple._id}/tags/xyz`)
140
143
  .send({tags: "unhealthy"})
141
144
  .expect(404);
142
- expect(res.body.title).toBe("Could not find tags/xyz");
145
+ expect(res.body.title).toBe("Array item not found");
146
+ expect(res.body.detail).toBe("Could not find tags/xyz");
143
147
  res = await agent
144
148
  .patch(`/food/${apple._id}/tags/healthy`)
145
149
  .send({tags: "unhealthy"})
@@ -149,7 +153,8 @@ describe("model array operations", () => {
149
153
 
150
154
  it("delete array item", async () => {
151
155
  let res = await agent.delete(`/food/${apple._id}/tags/xyz`).expect(404);
152
- expect(res.body.title).toBe("Could not find tags/xyz");
156
+ expect(res.body.title).toBe("Array item not found");
157
+ expect(res.body.detail).toBe("Could not find tags/xyz");
153
158
  res = await agent.delete(`/food/${apple._id}/tags/healthy`).expect(200);
154
159
  expect(res.body.data.tags).toEqual(["cheap"]);
155
160
  });
@@ -516,7 +521,8 @@ describe("array operation errors", () => {
516
521
  agent = await authAsUser(app, "notAdmin");
517
522
 
518
523
  const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(405);
519
- expect(res.body.title).toContain("Access to PATCH");
524
+ expect(res.body.title).toBe("Access denied");
525
+ expect(res.body.detail).toContain("Access to PATCH");
520
526
  });
521
527
 
522
528
  it("array operation on non-existent document returns 404", async () => {
@@ -538,7 +544,8 @@ describe("array operation errors", () => {
538
544
 
539
545
  const fakeId = "000000000000000000000000";
540
546
  const res = await agent.post(`/food/${fakeId}/tags`).send({tags: "organic"}).expect(404);
541
- expect(res.body.title).toContain("Could not find document to PATCH");
547
+ expect(res.body.title).toBe("Document not found");
548
+ expect(res.body.detail).toContain("Could not find document to PATCH");
542
549
  });
543
550
 
544
551
  it("array operation denied when user cannot update specific doc", async () => {
@@ -561,7 +568,8 @@ describe("array operation errors", () => {
561
568
  agent = await authAsUser(app, "notAdmin");
562
569
 
563
570
  const res = await agent.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(403);
564
- expect(res.body.title).toContain("Patch not allowed");
571
+ expect(res.body.title).toBe("Update not allowed");
572
+ expect(res.body.detail).toContain("Patch not allowed");
565
573
  });
566
574
 
567
575
  it("array operation transform error is handled", async () => {
@@ -1,15 +1,13 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {beforeEach, describe, expect, it} from "bun:test";
4
2
  import type express from "express";
5
- import mongoose from "mongoose";
3
+ import mongoose, {type HydratedDocument} from "mongoose";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
7
  import {modelRouter} from "./api";
10
- import {addAuthRoutes, setupAuth} from "./auth";
8
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
11
9
  import {Permissions} from "./permissions";
12
- import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
10
+ import {type Food, FoodModel, getBaseServer, setupDb, type User, UserModel} from "./tests";
13
11
 
14
12
  // A model without the isDeleted plugin so deletes call doc.deleteOne(). The
15
13
  // document delete hook throws to exercise the hard-delete error branch.
@@ -24,7 +22,7 @@ const ExplosiveModel = mongoose.model<{name: string}>("ExplosiveCoverage", explo
24
22
  describe("modelRouter error path coverage", () => {
25
23
  let server: TestAgent;
26
24
  let app: express.Application;
27
- let admin: any;
25
+ let admin: HydratedDocument<User>;
28
26
  let apple: Food;
29
27
 
30
28
  beforeEach(async () => {
@@ -44,8 +42,8 @@ describe("modelRouter error path coverage", () => {
44
42
  });
45
43
 
46
44
  app = getBaseServer();
47
- setupAuth(app, UserModel as any);
48
- addAuthRoutes(app, UserModel as any);
45
+ setupAuth(app, UserModel as unknown as AuthUserModel);
46
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
49
47
  });
50
48
 
51
49
  it("returns 400 when an array operation transformer throws a non-APIError", async () => {
@@ -96,14 +94,15 @@ describe("modelRouter error path coverage", () => {
96
94
  .post(`/food/${apple._id}/eatenBy`)
97
95
  .send({eatenBy: "not-an-object-id"})
98
96
  .expect(400);
99
- expect(res.body.title).toContain("PATCH Pre Update error");
97
+ expect(res.body.title).toBe("Validation failed");
98
+ expect(res.body.meta.fields["eatenBy.0"]).toContain("ObjectId");
100
99
  });
101
100
 
102
101
  it("returns 400 when a hard delete (no isDeleted plugin) fails", async () => {
103
102
  const doc = await ExplosiveModel.create({name: "boom"});
104
103
  app.use(
105
104
  "/explosive",
106
- modelRouter(ExplosiveModel as any, {
105
+ modelRouter(ExplosiveModel, {
107
106
  allowAnonymous: true,
108
107
  permissions: {
109
108
  create: [Permissions.IsAny],
@@ -2,14 +2,16 @@ import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
2
2
  import * as Sentry from "@sentry/bun";
3
3
  import {assert} from "chai";
4
4
  import type express from "express";
5
+ import {DateTime} from "luxon";
5
6
  import mongoose from "mongoose";
6
7
  import supertest from "supertest";
7
8
  import type TestAgent from "supertest/lib/agent";
8
9
 
9
- import {type ModelRouterOptions, modelRouter} from "./api";
10
+ import {type JSONValue, type ModelRouterOptions, modelRouter} from "./api";
10
11
  import {addAuthRoutes, setupAuth} from "./auth";
12
+ import {ConflictError} from "./errors";
11
13
  import {Permissions} from "./permissions";
12
- import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
14
+ import {type Food, FoodModel, getBaseServer, RequiredModel, setupDb, UserModel} from "./tests";
13
15
 
14
16
  type SetupAuthUserModel = Parameters<typeof setupAuth>[1];
15
17
  const authUserModel = UserModel as unknown as SetupAuthUserModel;
@@ -155,7 +157,7 @@ describe("modelRouter error paths", () => {
155
157
  assert.include(res.body.detail, "transform exploded");
156
158
  });
157
159
 
158
- it("wraps save failures during array operations", async () => {
160
+ it("converts Mongoose save failures during array operations into field errors", async () => {
159
161
  mountFood();
160
162
  const food = await FoodModel.create({
161
163
  calories: 1,
@@ -168,6 +170,360 @@ describe("modelRouter error paths", () => {
168
170
  .post(`/food/${food._id}/eatenBy`)
169
171
  .send({eatenBy: "not-an-object-id"})
170
172
  .expect(400);
171
- assert.include(res.body.title, "PATCH Pre Update error");
173
+ assert.equal(res.body.title, "Validation failed");
174
+ assert.include(res.body.meta.fields["eatenBy.0"], "ObjectId");
175
+ });
176
+
177
+ it("wraps non-Mongoose save failures during array operations", async () => {
178
+ mountFood();
179
+ const food = await FoodModel.create({
180
+ calories: 1,
181
+ name: "Unsavable",
182
+ ownerId: new mongoose.Types.ObjectId(),
183
+ } as Partial<Food>);
184
+
185
+ const saveSpy = spyOn(FoodModel.prototype, "save").mockImplementation(() => {
186
+ throw new Error("save exploded");
187
+ });
188
+ try {
189
+ const res = await server.post(`/food/${food._id}/tags`).send({tags: "vegetable"}).expect(400);
190
+ assert.include(res.body.title, "PATCH Pre Update error");
191
+ assert.include(res.body.detail, "save exploded");
192
+ } finally {
193
+ saveSpy.mockRestore();
194
+ }
195
+ });
196
+
197
+ it("wraps failures while assembling the list response", async () => {
198
+ mountFood({
199
+ responseHandler: async (data) => {
200
+ const serialized = [...(data as Food[])] as Food[] & {slice: () => never};
201
+ serialized.slice = () => {
202
+ throw new Error("slice exploded");
203
+ };
204
+ return serialized as unknown as JSONValue;
205
+ },
206
+ });
207
+ const ownerId = new mongoose.Types.ObjectId();
208
+ await FoodModel.create([
209
+ {calories: 1, name: "First", ownerId},
210
+ {calories: 2, name: "Second", ownerId},
211
+ ] as Partial<Food>[]);
212
+
213
+ // limit=1 fetches an extra doc, so the handler slices off the overflow.
214
+ const res = await server.get("/food?limit=1");
215
+ assert.equal(res.body.title, "Serialization error");
216
+ assert.include(res.body.detail, "slice exploded");
217
+ });
218
+
219
+ it("rejects a patch when the stored timestamp cannot be parsed", async () => {
220
+ // `updated` is a string here so the router has to parse it as an ISO date.
221
+ const timestampSchema = new mongoose.Schema({
222
+ name: {description: "The name", type: String},
223
+ updated: {description: "Last update, as an ISO string", type: String},
224
+ });
225
+ const TimestampModel = mongoose.model(`StringTimestamp_${Date.now()}`, timestampSchema);
226
+ app.use(
227
+ "/timestamped",
228
+ modelRouter(TimestampModel, {allowAnonymous: true, permissions: anyPermissions})
229
+ );
230
+ server = supertest(app);
231
+
232
+ const doc = await TimestampModel.create({name: "Timeless", updated: "not-a-date"});
233
+
234
+ const res = await server
235
+ .patch(`/timestamped/${doc._id}`)
236
+ .set("If-Unmodified-Since", DateTime.now().toHTTP() as string)
237
+ .send({name: "Renamed"})
238
+ .expect(400);
239
+ assert.equal(res.body.title, "Invalid server timestamp");
240
+ });
241
+ });
242
+
243
+ interface Guarded {
244
+ name: string;
245
+ tags: string[];
246
+ }
247
+
248
+ // A domain error of the shape consumers throw: stable title, kebab-case code, per-occurrence
249
+ // detail, and structured meta the client renders.
250
+ const staffConflictError = (code: string): ConflictError =>
251
+ new ConflictError({
252
+ code,
253
+ detail: "Conflict detected for Dr. Ada on 2026-07-31",
254
+ meta: {date: "2026-07-31", staff: "Dr. Ada"},
255
+ title: "Conflict detected",
256
+ });
257
+
258
+ const assertStaffConflict = (body: Record<string, unknown>, code: string): void => {
259
+ assert.equal(body.status, 409);
260
+ assert.equal(body.title, "Conflict detected");
261
+ assert.equal(body.detail, "Conflict detected for Dr. Ada on 2026-07-31");
262
+ assert.equal(body.code, code);
263
+ assert.deepEqual(body.meta, {date: "2026-07-31", staff: "Dr. Ada"});
264
+ };
265
+
266
+ const guardedSchema = new mongoose.Schema<Guarded>(
267
+ {
268
+ name: {description: "The name", type: String},
269
+ tags: {description: "Tags for the document", type: [String]},
270
+ },
271
+ {strict: "throw"}
272
+ );
273
+
274
+ // Stands in for a consumer model that validates in document middleware.
275
+ guardedSchema.pre("save", function () {
276
+ if (this.name === "Conflict" || this.tags?.includes("conflict")) {
277
+ throw staffConflictError("schedule-item-staff-conflict");
278
+ }
279
+ if (this.name === "Boom" || this.tags?.includes("boom")) {
280
+ throw new Error("save exploded");
281
+ }
282
+ });
283
+
284
+ const GuardedModel = mongoose.model<Guarded>("PassthroughGuarded", guardedSchema);
285
+
286
+ describe("modelRouter APIError passthrough", () => {
287
+ let app: express.Application;
288
+ let server: TestAgent;
289
+
290
+ beforeEach(async () => {
291
+ await setupDb();
292
+ await GuardedModel.deleteMany({});
293
+ app = getBaseServer();
294
+ setupAuth(app, authUserModel);
295
+ addAuthRoutes(app, authUserModel);
296
+ });
297
+
298
+ const mountGuarded = (options: Partial<ModelRouterOptions<Guarded>> = {}): void => {
299
+ app.use(
300
+ "/guarded",
301
+ modelRouter(GuardedModel, {
302
+ allowAnonymous: true,
303
+ permissions: anyPermissions,
304
+ ...options,
305
+ })
306
+ );
307
+ server = supertest(app);
308
+ };
309
+
310
+ describe("Mongoose document middleware", () => {
311
+ it("keeps an APIError from pre(save) intact through POST /", async () => {
312
+ mountGuarded();
313
+ const res = await server.post("/guarded").send({name: "Conflict"}).expect(409);
314
+ assertStaffConflict(res.body, "schedule-item-staff-conflict");
315
+ });
316
+
317
+ it("wraps a non-APIError from pre(save) on POST /", async () => {
318
+ mountGuarded();
319
+ const res = await server.post("/guarded").send({name: "Boom"}).expect(400);
320
+ assert.equal(res.body.title, "Create error");
321
+ assert.equal(res.body.code, "create-error");
322
+ assert.include(res.body.detail, "save exploded");
323
+ });
324
+
325
+ it("keeps an APIError from pre(save) intact through PATCH /:id", async () => {
326
+ mountGuarded();
327
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
328
+ const res = await server.patch(`/guarded/${doc._id}`).send({name: "Conflict"}).expect(409);
329
+ assertStaffConflict(res.body, "schedule-item-staff-conflict");
330
+ });
331
+
332
+ it("wraps a non-APIError from pre(save) on PATCH /:id", async () => {
333
+ mountGuarded();
334
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
335
+ const res = await server.patch(`/guarded/${doc._id}`).send({name: "Boom"}).expect(400);
336
+ assert.equal(res.body.title, "preUpdate hook save error");
337
+ assert.include(res.body.detail, "save exploded");
338
+ });
339
+
340
+ it("keeps an APIError from pre(save) intact through an array operation", async () => {
341
+ mountGuarded();
342
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
343
+ const res = await server
344
+ .post(`/guarded/${doc._id}/tags`)
345
+ .send({tags: "conflict"})
346
+ .expect(409);
347
+ assertStaffConflict(res.body, "schedule-item-staff-conflict");
348
+ });
349
+
350
+ it("surfaces Mongoose validation errors from create as per-field errors", async () => {
351
+ app.use(
352
+ "/required",
353
+ modelRouter(RequiredModel, {allowAnonymous: true, permissions: anyPermissions})
354
+ );
355
+ server = supertest(app);
356
+
357
+ const res = await server.post("/required").send({about: "no name here"}).expect(400);
358
+ assert.equal(res.body.title, "Validation failed");
359
+ assert.include(res.body.meta.fields.name, "required");
360
+ assert.isTrue(res.body.disableExternalErrorTracking);
361
+ });
362
+ });
363
+
364
+ describe("hooks", () => {
365
+ it("keeps an APIError from queryFilter intact", async () => {
366
+ mountGuarded({
367
+ queryFilter: () => {
368
+ throw staffConflictError("query-filter-conflict");
369
+ },
370
+ });
371
+ const res = await server.get("/guarded").expect(409);
372
+ assertStaffConflict(res.body, "query-filter-conflict");
373
+ });
374
+
375
+ it("wraps a non-APIError from queryFilter with the caught error's message", async () => {
376
+ mountGuarded({
377
+ queryFilter: () => {
378
+ throw new Error("filter exploded");
379
+ },
380
+ });
381
+ const res = await server.get("/guarded").expect(400);
382
+ assert.equal(res.body.title, "Query filter error");
383
+ // Previously String(error), which prefixed the class name.
384
+ assert.equal(res.body.detail, "filter exploded");
385
+ });
386
+
387
+ it("wraps a thrown non-Error from queryFilter", async () => {
388
+ mountGuarded({
389
+ queryFilter: () => {
390
+ throw "filter string";
391
+ },
392
+ });
393
+ const res = await server.get("/guarded").expect(400);
394
+ assert.equal(res.body.title, "Query filter error");
395
+ assert.equal(res.body.detail, "filter string");
396
+ });
397
+
398
+ it("keeps an APIError from responseHandler intact for every method", async () => {
399
+ mountGuarded({
400
+ responseHandler: () => {
401
+ throw staffConflictError("response-handler-conflict");
402
+ },
403
+ });
404
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
405
+
406
+ for (const request of [
407
+ server.post("/guarded").send({name: "Another"}),
408
+ server.get("/guarded"),
409
+ server.get(`/guarded/${doc._id}`),
410
+ server.patch(`/guarded/${doc._id}`).send({name: "Renamed"}),
411
+ ]) {
412
+ const res = await request.expect(409);
413
+ assertStaffConflict(res.body, "response-handler-conflict");
414
+ }
415
+ });
416
+
417
+ it("wraps a non-APIError from responseHandler", async () => {
418
+ mountGuarded({
419
+ responseHandler: () => {
420
+ throw new Error("serialize exploded");
421
+ },
422
+ });
423
+ const res = await server.get("/guarded").expect(500);
424
+ assert.equal(res.body.title, "responseHandler error");
425
+ assert.include(res.body.detail, "serialize exploded");
426
+ });
427
+
428
+ it("keeps an APIError from postCreate intact", async () => {
429
+ mountGuarded({
430
+ postCreate: () => {
431
+ throw staffConflictError("post-create-conflict");
432
+ },
433
+ });
434
+ const res = await server.post("/guarded").send({name: "Fine"}).expect(409);
435
+ assertStaffConflict(res.body, "post-create-conflict");
436
+ });
437
+
438
+ it("wraps a non-APIError from postCreate", async () => {
439
+ mountGuarded({
440
+ postCreate: () => {
441
+ throw new Error("postCreate exploded");
442
+ },
443
+ });
444
+ const res = await server.post("/guarded").send({name: "Fine"}).expect(400);
445
+ assert.equal(res.body.title, "postCreate hook error");
446
+ assert.include(res.body.detail, "postCreate exploded");
447
+ });
448
+
449
+ it("keeps an APIError from postUpdate intact", async () => {
450
+ mountGuarded({
451
+ postUpdate: () => {
452
+ throw staffConflictError("post-update-conflict");
453
+ },
454
+ });
455
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
456
+ const res = await server.patch(`/guarded/${doc._id}`).send({name: "Renamed"}).expect(409);
457
+ assertStaffConflict(res.body, "post-update-conflict");
458
+ });
459
+
460
+ it("wraps a non-APIError from postUpdate", async () => {
461
+ mountGuarded({
462
+ postUpdate: () => {
463
+ throw new Error("postUpdate exploded");
464
+ },
465
+ });
466
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
467
+ const res = await server.patch(`/guarded/${doc._id}`).send({name: "Renamed"}).expect(400);
468
+ assert.equal(res.body.title, "postUpdate hook error");
469
+ assert.include(res.body.detail, "postUpdate exploded");
470
+ });
471
+
472
+ it("keeps an APIError from postDelete intact", async () => {
473
+ mountGuarded({
474
+ postDelete: () => {
475
+ throw staffConflictError("post-delete-conflict");
476
+ },
477
+ });
478
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
479
+ const res = await server.delete(`/guarded/${doc._id}`).expect(409);
480
+ assertStaffConflict(res.body, "post-delete-conflict");
481
+ });
482
+
483
+ it("wraps a non-APIError from postDelete", async () => {
484
+ mountGuarded({
485
+ postDelete: () => {
486
+ throw new Error("postDelete exploded");
487
+ },
488
+ });
489
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
490
+ const res = await server.delete(`/guarded/${doc._id}`).expect(400);
491
+ assert.equal(res.body.title, "postDelete hook error");
492
+ assert.include(res.body.detail, "postDelete exploded");
493
+ });
494
+
495
+ it("keeps an APIError from preUpdate intact during an array operation", async () => {
496
+ mountGuarded({
497
+ preUpdate: () => {
498
+ throw staffConflictError("array-pre-update-conflict");
499
+ },
500
+ });
501
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
502
+ const res = await server.post(`/guarded/${doc._id}/tags`).send({tags: "healthy"}).expect(409);
503
+ assertStaffConflict(res.body, "array-pre-update-conflict");
504
+ });
505
+
506
+ it("keeps an APIError from postUpdate intact during an array operation", async () => {
507
+ mountGuarded({
508
+ postUpdate: () => {
509
+ throw staffConflictError("array-post-update-conflict");
510
+ },
511
+ });
512
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
513
+ const res = await server.post(`/guarded/${doc._id}/tags`).send({tags: "healthy"}).expect(409);
514
+ assertStaffConflict(res.body, "array-post-update-conflict");
515
+ });
516
+
517
+ it("wraps a non-APIError from preUpdate during an array operation", async () => {
518
+ mountGuarded({
519
+ preUpdate: () => {
520
+ throw new Error("array preUpdate exploded");
521
+ },
522
+ });
523
+ const doc = await GuardedModel.create({name: "Fine", tags: []});
524
+ const res = await server.post(`/guarded/${doc._id}/tags`).send({tags: "healthy"}).expect(400);
525
+ assert.equal(res.body.title, "preUpdate hook error");
526
+ assert.include(res.body.detail, "array preUpdate exploded");
527
+ });
172
528
  });
173
529
  });
@@ -1,6 +1,7 @@
1
1
  // noExplicitAny: test mock typing
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
3
  import {describe, expect, it} from "bun:test";
4
+ import type {NextFunction} from "express";
4
5
  import mongoose from "mongoose";
5
6
 
6
7
  import {
@@ -153,5 +154,16 @@ describe("errors module", () => {
153
154
  apiUnauthorizedMiddleware(err, {} as any, {} as any, next);
154
155
  expect(nextCalled).toBe(true);
155
156
  });
157
+
158
+ it("calls next for an APIError whose title is Unauthorized", () => {
159
+ const err = new APIError({code: "not-a-member", status: 403, title: "Unauthorized"});
160
+ let nextArg: unknown;
161
+ const next = (error?: unknown) => {
162
+ nextArg = error;
163
+ };
164
+
165
+ apiUnauthorizedMiddleware(err, {} as any, {} as any, next as unknown as NextFunction);
166
+ expect(nextArg).toBe(err);
167
+ });
156
168
  });
157
169
  });
@@ -178,12 +178,16 @@ describe("query and list methods", () => {
178
178
 
179
179
  it("list page 0 ", async () => {
180
180
  const res = await agent.get("/food?limit=1&page=0").expect(400);
181
- expect(res.body.title).toBe("Invalid page: 0");
181
+ expect(res.body.title).toBe("Invalid page");
182
+ expect(res.body.detail).toBe("Invalid page: 0");
183
+ expect(res.body.source).toEqual({parameter: "page"});
182
184
  });
183
185
 
184
186
  it("list page with garbage ", async () => {
185
187
  const res = await agent.get("/food?limit=1&page=abc").expect(400);
186
- expect(res.body.title).toBe("Invalid page: abc");
188
+ expect(res.body.title).toBe("Invalid page");
189
+ expect(res.body.detail).toBe("Invalid page: abc");
190
+ expect(res.body.source).toEqual({parameter: "page"});
187
191
  });
188
192
 
189
193
  it("list page over", async () => {
@@ -216,7 +220,9 @@ describe("query and list methods", () => {
216
220
 
217
221
  it("list returns 400 when created_gte is not a valid date", async () => {
218
222
  const res = await agent.get("/food").query({created_gte: "not-a-date", limit: 10}).expect(400);
219
- expect(res.body.title).toBe("Invalid date for query parameter created_gte");
223
+ expect(res.body.title).toBe("Invalid date query parameter");
224
+ expect(res.body.detail).toBe("Invalid date for query parameter created_gte");
225
+ expect(res.body.source).toEqual({parameter: "created_gte"});
220
226
  });
221
227
 
222
228
  it("list returns 400 when created_lte is not a valid date", async () => {
@@ -224,7 +230,9 @@ describe("query and list methods", () => {
224
230
  .get("/food")
225
231
  .query({created_lte: "also-not-a-date", limit: 10})
226
232
  .expect(400);
227
- expect(res.body.title).toBe("Invalid date for query parameter created_lte");
233
+ expect(res.body.title).toBe("Invalid date query parameter");
234
+ expect(res.body.detail).toBe("Invalid date for query parameter created_lte");
235
+ expect(res.body.source).toEqual({parameter: "created_lte"});
228
236
  });
229
237
 
230
238
  it("applies created_gte alone as a lower Date bound", async () => {
@@ -275,7 +283,8 @@ describe("query and list methods", () => {
275
283
 
276
284
  it("list query params not in list", async () => {
277
285
  const res = await agent.get(`/food?ownerId=${admin._id}`).expect(400);
278
- expect(res.body.title).toBe("ownerId is not allowed as a query param.");
286
+ expect(res.body.title).toBe("Query parameter not allowed");
287
+ expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
279
288
  });
280
289
 
281
290
  it("list query by nested param", async () => {
@@ -477,16 +486,19 @@ describe("query and list methods", () => {
477
486
  let res = await agent
478
487
  .get(`/food?${qs.stringify({$and: [{ownerId: "healthy"}, {tags: "cheap"}]})}`)
479
488
  .expect(400);
480
- expect(res.body.title).toBe("ownerId is not allowed as a query param.");
489
+ expect(res.body.title).toBe("Query parameter not allowed");
490
+ expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
481
491
  res = await agent
482
492
  .get(`/food?${qs.stringify({$and: [{tags: "cheap"}, {ownerId: "healthy"}]})}`)
483
493
  .expect(400);
484
- expect(res.body.title).toBe("ownerId is not allowed as a query param.");
494
+ expect(res.body.title).toBe("Query parameter not allowed");
495
+ expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
485
496
 
486
497
  res = await agent
487
498
  .get(`/food?${qs.stringify({$or: [{tags: "cheap"}, {ownerId: "healthy"}]})}`)
488
499
  .expect(400);
489
- expect(res.body.title).toBe("ownerId is not allowed as a query param.");
500
+ expect(res.body.title).toBe("Query parameter not allowed");
501
+ expect(res.body.detail).toBe("ownerId is not allowed as a query param.");
490
502
  });
491
503
 
492
504
  it("query with a number", async () => {