@terreno/api 0.26.0 → 0.27.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.
- package/dist/__tests__/openApiCompat.test.js +8 -2
- package/dist/actions.openApi.test.js +1 -0
- package/dist/actions.test.js +1 -0
- package/dist/api.arrayOperations.test.js +1 -0
- package/dist/api.coverage.test.d.ts +1 -0
- package/dist/api.coverage.test.js +191 -0
- package/dist/api.errorPaths.test.d.ts +1 -0
- package/dist/api.errorPaths.test.js +278 -0
- package/dist/api.errors.test.js +1 -0
- package/dist/api.hooks.test.js +1 -0
- package/dist/api.js +160 -167
- package/dist/api.query.test.js +1 -0
- package/dist/api.test.js +1 -0
- package/dist/auth.js +1 -0
- package/dist/auth.test.js +122 -0
- package/dist/betterAuthSetup.js +1 -0
- package/dist/betterAuthSetup.test.js +1 -0
- package/dist/configuration.test.js +1 -0
- package/dist/configurationApp.js +1 -0
- package/dist/configurationPlugin.test.js +80 -0
- package/dist/consentApp.test.js +1 -0
- package/dist/docLoader.js +1 -3
- package/dist/envConfigurationPlugin.js +1 -0
- package/dist/example.js +3 -2
- package/dist/expressServer.test.js +1 -0
- package/dist/githubAuth.js +2 -0
- package/dist/githubAuth.test.js +1 -0
- package/dist/logger.test.js +107 -0
- package/dist/openApi.test.js +1 -0
- package/dist/openApiBuilder.js +2 -1
- package/dist/openApiBuilder.test.js +3 -2
- package/dist/openApiValidator.js +1 -0
- package/dist/openApiValidator.test.js +41 -0
- package/dist/permissions.middleware.test.js +1 -0
- package/dist/permissions.test.js +1 -0
- package/dist/plugins.js +8 -0
- package/dist/plugins.test.js +1 -0
- package/dist/populate.js +4 -2
- package/dist/populate.test.js +1 -0
- package/dist/realtime/realtime.test.js +13 -3
- package/dist/realtime/types.d.ts +1 -1
- package/dist/requestContext.test.js +28 -0
- package/dist/terrenoApp.js +1 -0
- package/dist/tests/createTestData.js +11 -6
- package/dist/tests/models.js +1 -0
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +3 -1
- package/package.json +7 -7
- package/src/__tests__/openApiCompat.test.ts +8 -2
- package/src/actions.openApi.test.ts +1 -0
- package/src/actions.test.ts +1 -0
- package/src/api.arrayOperations.test.ts +1 -0
- package/src/api.coverage.test.ts +121 -0
- package/src/api.errorPaths.test.ts +171 -0
- package/src/api.errors.test.ts +1 -0
- package/src/api.hooks.test.ts +1 -0
- package/src/api.query.test.ts +1 -0
- package/src/api.test.ts +1 -0
- package/src/api.ts +13 -9
- package/src/auth.test.ts +91 -2
- package/src/auth.ts +6 -0
- package/src/betterAuthSetup.test.ts +1 -0
- package/src/betterAuthSetup.ts +3 -0
- package/src/configuration.test.ts +1 -0
- package/src/configurationApp.ts +2 -0
- package/src/configurationPlugin.test.ts +46 -1
- package/src/consentApp.test.ts +1 -0
- package/src/docLoader.ts +1 -2
- package/src/envConfigurationPlugin.ts +2 -0
- package/src/example.ts +3 -2
- package/src/expressServer.test.ts +1 -0
- package/src/expressServer.ts +4 -2
- package/src/githubAuth.test.ts +1 -0
- package/src/githubAuth.ts +2 -0
- package/src/logger.test.ts +78 -0
- package/src/openApi.test.ts +1 -0
- package/src/openApiBuilder.test.ts +7 -6
- package/src/openApiBuilder.ts +2 -1
- package/src/openApiValidator.test.ts +64 -0
- package/src/openApiValidator.ts +1 -0
- package/src/permissions.middleware.test.ts +1 -0
- package/src/permissions.test.ts +1 -0
- package/src/plugins.test.ts +1 -0
- package/src/plugins.ts +9 -0
- package/src/populate.test.ts +1 -0
- package/src/populate.ts +4 -2
- package/src/realtime/realtime.test.ts +13 -3
- package/src/realtime/realtimeApp.ts +1 -0
- package/src/realtime/registry.ts +1 -0
- package/src/realtime/types.ts +1 -2
- package/src/requestContext.test.ts +32 -0
- package/src/terrenoApp.ts +1 -0
- package/src/tests/createTestData.ts +11 -6
- package/src/tests/models.ts +1 -0
- package/src/vendor/wesleytodd-openapi/lib/generate-doc.js +4 -1
- package/tsconfig.json +3 -3
- /package/{types.d.ts → src/types.d.ts} +0 -0
|
@@ -53,6 +53,8 @@ var __read = (this && this.__read) || function (o, n) {
|
|
|
53
53
|
};
|
|
54
54
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
55
55
|
exports.loadTestDataFromDocuments = exports.toCachedTestData = exports.createTestData = exports.createRequiredFixtures = exports.createStandardFoods = exports.createTestUsers = exports.clearTestCollections = void 0;
|
|
56
|
+
var luxon_1 = require("luxon");
|
|
57
|
+
var errors_1 = require("../errors");
|
|
56
58
|
var logger_1 = require("../logger");
|
|
57
59
|
var models_1 = require("./models");
|
|
58
60
|
var setPassword = function (user, password) { return __awaiter(void 0, void 0, void 0, function () {
|
|
@@ -116,12 +118,12 @@ var createStandardFoods = function (users) { return __awaiter(void 0, void 0, vo
|
|
|
116
118
|
models_1.FoodModel.create({
|
|
117
119
|
calories: 1,
|
|
118
120
|
categories: [{ name: "Vegetables", show: true }],
|
|
119
|
-
created:
|
|
121
|
+
created: luxon_1.DateTime.fromISO("2021-12-03T00:00:20.000Z").toJSDate(),
|
|
120
122
|
eatenBy: [admin._id],
|
|
121
123
|
expiration: "2026-12-31",
|
|
122
124
|
hidden: false,
|
|
123
125
|
lastEatenWith: {
|
|
124
|
-
dressing:
|
|
126
|
+
dressing: luxon_1.DateTime.fromISO("2021-12-03T19:00:30.000Z").toJSDate(),
|
|
125
127
|
},
|
|
126
128
|
likesIds: [
|
|
127
129
|
{ likes: true, userId: admin._id },
|
|
@@ -138,7 +140,7 @@ var createStandardFoods = function (users) { return __awaiter(void 0, void 0, vo
|
|
|
138
140
|
}),
|
|
139
141
|
models_1.FoodModel.create({
|
|
140
142
|
calories: 100,
|
|
141
|
-
created:
|
|
143
|
+
created: luxon_1.DateTime.fromISO("2021-12-03T00:00:30.000Z").toJSDate(),
|
|
142
144
|
expiration: "2026-12-31",
|
|
143
145
|
hidden: true,
|
|
144
146
|
likesIds: [{ likes: true, userId: admin._id }],
|
|
@@ -149,7 +151,7 @@ var createStandardFoods = function (users) { return __awaiter(void 0, void 0, vo
|
|
|
149
151
|
}),
|
|
150
152
|
models_1.FoodModel.create({
|
|
151
153
|
calories: 100,
|
|
152
|
-
created:
|
|
154
|
+
created: luxon_1.DateTime.fromISO("2021-12-03T00:00:00.000Z").toJSDate(),
|
|
153
155
|
eatenBy: [admin._id, notAdmin._id],
|
|
154
156
|
expiration: "2026-12-31",
|
|
155
157
|
hidden: false,
|
|
@@ -161,7 +163,7 @@ var createStandardFoods = function (users) { return __awaiter(void 0, void 0, vo
|
|
|
161
163
|
}),
|
|
162
164
|
models_1.FoodModel.create({
|
|
163
165
|
calories: 800,
|
|
164
|
-
created:
|
|
166
|
+
created: luxon_1.DateTime.fromISO("2022-01-01T00:00:00.000Z").toJSDate(),
|
|
165
167
|
expiration: "2026-12-31",
|
|
166
168
|
hidden: false,
|
|
167
169
|
likesIds: [{ likes: true, userId: adminOther._id }],
|
|
@@ -259,7 +261,10 @@ var loadTestDataFromDocuments = function (cached) { return __awaiter(void 0, voi
|
|
|
259
261
|
!pizza ||
|
|
260
262
|
!sample ||
|
|
261
263
|
!withAbout) {
|
|
262
|
-
throw new
|
|
264
|
+
throw new errors_1.APIError({
|
|
265
|
+
status: 500,
|
|
266
|
+
title: "[createTestData] Cached test data references missing documents",
|
|
267
|
+
});
|
|
263
268
|
}
|
|
264
269
|
return [2 /*return*/, {
|
|
265
270
|
foods: { apple: apple, carrots: carrots, pizza: pizza, spinach: spinach },
|
package/dist/tests/models.js
CHANGED
|
@@ -101,6 +101,7 @@ var foodSchema = new mongoose_1.Schema({
|
|
|
101
101
|
type: mongoose_1.Schema.Types.ObjectId,
|
|
102
102
|
},
|
|
103
103
|
],
|
|
104
|
+
// noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
|
|
104
105
|
// biome-ignore lint/suspicious/noExplicitAny: DateOnly is a custom SchemaType not recognized by Mongoose's built-in type definitions
|
|
105
106
|
expiration: { description: "Expiration date of the food", type: plugins_1.DateOnly },
|
|
106
107
|
hidden: {
|
|
@@ -70,7 +70,7 @@ module.exports = function generateDocument(baseDocument, router, basePath) {
|
|
|
70
70
|
}
|
|
71
71
|
operation.parameters = params_1.filter(function (p) { return typeof p.name === 'string' && p.name; });
|
|
72
72
|
try {
|
|
73
|
-
path = pathToRegexp.compile(path.replace(/\*|\(\*\)/g, '(.*)')
|
|
73
|
+
path = pathToRegexp.compile(path.replace(/\*|\(\*\)/g, '(.*)'), { encode: function (value) { return value; } })(keys_1);
|
|
74
74
|
}
|
|
75
75
|
catch (_e) {
|
|
76
76
|
// Express 5 stores path params in matchers instead of layer.keys, so keys
|
|
@@ -78,6 +78,8 @@ module.exports = function generateDocument(baseDocument, router, basePath) {
|
|
|
78
78
|
path = path.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
|
+
// Normalize any percent-encoded path parameters to OpenAPI syntax.
|
|
82
|
+
path = path.replace(/%7B/gi, '{').replace(/%7D/gi, '}');
|
|
81
83
|
doc.paths[path] = doc.paths[path] || {};
|
|
82
84
|
doc.paths[path][layer.method] = operation;
|
|
83
85
|
setSchema(layer.handle, operation);
|
package/package.json
CHANGED
|
@@ -7,15 +7,15 @@
|
|
|
7
7
|
"@asteasolutions/zod-to-openapi": "^8.5.0",
|
|
8
8
|
"@sentry/bun": "^10.39.0",
|
|
9
9
|
"@sentry/profiling-node": "^10.25.0",
|
|
10
|
-
"@terreno/test": "0.
|
|
10
|
+
"@terreno/test": "0.27.0",
|
|
11
11
|
"@types/qs": "^6.14.0",
|
|
12
|
-
"ajv": "8.
|
|
12
|
+
"ajv": "8.20.0",
|
|
13
13
|
"ajv-formats": "^3.0.1",
|
|
14
14
|
"ajv-keywords": "^5.1.0",
|
|
15
15
|
"http-errors": "^2.0.0",
|
|
16
|
-
"path-to-regexp": "^
|
|
16
|
+
"path-to-regexp": "^8.4.2",
|
|
17
17
|
"router": "^2.2.0",
|
|
18
|
-
"serve-static": "^
|
|
18
|
+
"serve-static": "^2.2.1",
|
|
19
19
|
"swagger-parser": "^10.0.3",
|
|
20
20
|
"swagger-ui-dist": "^5.11.8",
|
|
21
21
|
"yaml": "^2.4.0",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"express": "^5.2.1",
|
|
28
28
|
"generaterr": "^1.5.0",
|
|
29
29
|
"jsonwebtoken": "^9.0.2",
|
|
30
|
-
"lodash": "^4.
|
|
30
|
+
"lodash": "^4.18.1",
|
|
31
31
|
"luxon": "^3.7.2",
|
|
32
32
|
"mongoose-to-swagger": "^1.4.0",
|
|
33
33
|
"ms": "^2.1.3",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"@types/supertest": "^7.2.0",
|
|
67
67
|
"mongodb-memory-server": "^11.0.1",
|
|
68
68
|
"mongoose": "8.23.0",
|
|
69
|
-
"sinon": "^
|
|
69
|
+
"sinon": "^22.0.0",
|
|
70
70
|
"supertest": "^7.2.2",
|
|
71
71
|
"typedoc": "^0.28.17",
|
|
72
72
|
"typescript": "~5.9.2",
|
|
@@ -123,5 +123,5 @@
|
|
|
123
123
|
"updateSnapshot": "bun test --update-snapshots"
|
|
124
124
|
},
|
|
125
125
|
"types": "dist/index.d.ts",
|
|
126
|
-
"version": "0.
|
|
126
|
+
"version": "0.27.0"
|
|
127
127
|
}
|
|
@@ -203,7 +203,10 @@ describe("openApiCompat", () => {
|
|
|
203
203
|
const routeLayer = findLayer(stack, (layer) => layer.route?.path === "/items/:itemId");
|
|
204
204
|
expect(routeLayer).toBeDefined();
|
|
205
205
|
expect(routeLayer?.regexp).toBeInstanceOf(RegExp);
|
|
206
|
-
|
|
206
|
+
if (!(routeLayer?.regexp instanceof RegExp)) {
|
|
207
|
+
throw new Error("Expected the item route layer to have a regexp");
|
|
208
|
+
}
|
|
209
|
+
expect(routeLayer.regexp.test("/items/123")).toBe(true);
|
|
207
210
|
expect(routeLayer?.keys).toEqual([{name: "itemId", optional: false}]);
|
|
208
211
|
|
|
209
212
|
const res = await supertest(app).get("/items/123").expect(200);
|
|
@@ -275,7 +278,10 @@ describe("openApiCompat", () => {
|
|
|
275
278
|
const widgetLayer = findLayer(stack, (layer) => layer.route?.path === "/widgets/:widgetId");
|
|
276
279
|
expect(widgetLayer).toBeDefined();
|
|
277
280
|
expect(widgetLayer?.regexp).toBeInstanceOf(RegExp);
|
|
278
|
-
|
|
281
|
+
if (!(widgetLayer?.regexp instanceof RegExp)) {
|
|
282
|
+
throw new Error("Expected the widget route layer to have a regexp");
|
|
283
|
+
}
|
|
284
|
+
expect(widgetLayer.regexp.test("/widgets/42")).toBe(true);
|
|
279
285
|
expect(widgetLayer?.keys).toEqual([{name: "widgetId", optional: false}]);
|
|
280
286
|
});
|
|
281
287
|
|
package/src/actions.test.ts
CHANGED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// noExplicitAny: test mock typing
|
|
2
|
+
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
|
+
import {beforeEach, describe, expect, it} from "bun:test";
|
|
4
|
+
import type express from "express";
|
|
5
|
+
import mongoose from "mongoose";
|
|
6
|
+
import supertest from "supertest";
|
|
7
|
+
import type TestAgent from "supertest/lib/agent";
|
|
8
|
+
|
|
9
|
+
import {modelRouter} from "./api";
|
|
10
|
+
import {addAuthRoutes, setupAuth} from "./auth";
|
|
11
|
+
import {Permissions} from "./permissions";
|
|
12
|
+
import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
|
|
13
|
+
|
|
14
|
+
// A model without the isDeleted plugin so deletes call doc.deleteOne(). The
|
|
15
|
+
// document delete hook throws to exercise the hard-delete error branch.
|
|
16
|
+
const explosiveSchema = new mongoose.Schema<{name: string}>({
|
|
17
|
+
name: {description: "The name of the item", type: String},
|
|
18
|
+
});
|
|
19
|
+
explosiveSchema.pre("deleteOne", {document: true, query: false}, () => {
|
|
20
|
+
throw new Error("deleteOne exploded");
|
|
21
|
+
});
|
|
22
|
+
const ExplosiveModel = mongoose.model<{name: string}>("ExplosiveCoverage", explosiveSchema);
|
|
23
|
+
|
|
24
|
+
describe("modelRouter error path coverage", () => {
|
|
25
|
+
let server: TestAgent;
|
|
26
|
+
let app: express.Application;
|
|
27
|
+
let admin: any;
|
|
28
|
+
let apple: Food;
|
|
29
|
+
|
|
30
|
+
beforeEach(async () => {
|
|
31
|
+
[admin] = await setupDb();
|
|
32
|
+
|
|
33
|
+
apple = await FoodModel.create({
|
|
34
|
+
calories: 100,
|
|
35
|
+
categories: [
|
|
36
|
+
{name: "Fruit", show: true},
|
|
37
|
+
{name: "Popular", show: false},
|
|
38
|
+
],
|
|
39
|
+
created: new Date("2021-12-03T00:00:30.000Z"),
|
|
40
|
+
hidden: false,
|
|
41
|
+
name: "Apple",
|
|
42
|
+
ownerId: admin._id,
|
|
43
|
+
tags: ["healthy", "cheap"],
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
app = getBaseServer();
|
|
47
|
+
setupAuth(app, UserModel as any);
|
|
48
|
+
addAuthRoutes(app, UserModel as any);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it("returns 400 when an array operation transformer throws a non-APIError", async () => {
|
|
52
|
+
app.use(
|
|
53
|
+
"/food",
|
|
54
|
+
modelRouter(FoodModel, {
|
|
55
|
+
allowAnonymous: true,
|
|
56
|
+
permissions: {
|
|
57
|
+
create: [Permissions.IsAny],
|
|
58
|
+
delete: [Permissions.IsAny],
|
|
59
|
+
list: [Permissions.IsAny],
|
|
60
|
+
read: [Permissions.IsAny],
|
|
61
|
+
update: [Permissions.IsAny],
|
|
62
|
+
},
|
|
63
|
+
transformer: {
|
|
64
|
+
transform: () => {
|
|
65
|
+
throw new Error("array transform boom");
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
);
|
|
70
|
+
server = supertest(app);
|
|
71
|
+
|
|
72
|
+
const res = await server.post(`/food/${apple._id}/tags`).send({tags: "organic"}).expect(403);
|
|
73
|
+
expect(res.body.title).toContain("array transform boom");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("returns 400 when saving an array operation fails validation", async () => {
|
|
77
|
+
app.use(
|
|
78
|
+
"/food",
|
|
79
|
+
modelRouter(FoodModel, {
|
|
80
|
+
allowAnonymous: true,
|
|
81
|
+
permissions: {
|
|
82
|
+
create: [Permissions.IsAny],
|
|
83
|
+
delete: [Permissions.IsAny],
|
|
84
|
+
list: [Permissions.IsAny],
|
|
85
|
+
read: [Permissions.IsAny],
|
|
86
|
+
update: [Permissions.IsAny],
|
|
87
|
+
},
|
|
88
|
+
})
|
|
89
|
+
);
|
|
90
|
+
server = supertest(app);
|
|
91
|
+
|
|
92
|
+
// eatenBy is an ObjectId array; pushing a non-ObjectId value fails the
|
|
93
|
+
// cast when the document is saved.
|
|
94
|
+
const res = await server
|
|
95
|
+
.post(`/food/${apple._id}/eatenBy`)
|
|
96
|
+
.send({eatenBy: "not-an-object-id"})
|
|
97
|
+
.expect(400);
|
|
98
|
+
expect(res.body.title).toContain("PATCH Pre Update error");
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
it("returns 400 when a hard delete (no isDeleted plugin) fails", async () => {
|
|
102
|
+
const doc = await ExplosiveModel.create({name: "boom"});
|
|
103
|
+
app.use(
|
|
104
|
+
"/explosive",
|
|
105
|
+
modelRouter(ExplosiveModel as any, {
|
|
106
|
+
allowAnonymous: true,
|
|
107
|
+
permissions: {
|
|
108
|
+
create: [Permissions.IsAny],
|
|
109
|
+
delete: [Permissions.IsAny],
|
|
110
|
+
list: [Permissions.IsAny],
|
|
111
|
+
read: [Permissions.IsAny],
|
|
112
|
+
update: [Permissions.IsAny],
|
|
113
|
+
},
|
|
114
|
+
})
|
|
115
|
+
);
|
|
116
|
+
server = supertest(app);
|
|
117
|
+
|
|
118
|
+
const res = await server.delete(`/explosive/${doc._id}`).expect(400);
|
|
119
|
+
expect(res.body.title).toContain("deleteOne exploded");
|
|
120
|
+
});
|
|
121
|
+
});
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import {afterEach, beforeEach, describe, it, spyOn} from "bun:test";
|
|
2
|
+
import * as Sentry from "@sentry/bun";
|
|
3
|
+
import {assert} from "chai";
|
|
4
|
+
import type express from "express";
|
|
5
|
+
import mongoose from "mongoose";
|
|
6
|
+
import supertest from "supertest";
|
|
7
|
+
import type TestAgent from "supertest/lib/agent";
|
|
8
|
+
|
|
9
|
+
import {type ModelRouterOptions, modelRouter} from "./api";
|
|
10
|
+
import {addAuthRoutes, setupAuth} from "./auth";
|
|
11
|
+
import {Permissions} from "./permissions";
|
|
12
|
+
import {type Food, FoodModel, getBaseServer, setupDb, UserModel} from "./tests";
|
|
13
|
+
|
|
14
|
+
type SetupAuthUserModel = Parameters<typeof setupAuth>[1];
|
|
15
|
+
const authUserModel = UserModel as unknown as SetupAuthUserModel;
|
|
16
|
+
|
|
17
|
+
interface RestorableSpy {
|
|
18
|
+
mockRestore?: () => void;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const anyPermissions = {
|
|
22
|
+
create: [Permissions.IsAny],
|
|
23
|
+
delete: [Permissions.IsAny],
|
|
24
|
+
list: [Permissions.IsAny],
|
|
25
|
+
read: [Permissions.IsAny],
|
|
26
|
+
update: [Permissions.IsAny],
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
describe("modelRouter error paths", () => {
|
|
30
|
+
let app: express.Application;
|
|
31
|
+
let server: TestAgent;
|
|
32
|
+
|
|
33
|
+
beforeEach(async () => {
|
|
34
|
+
await setupDb();
|
|
35
|
+
app = getBaseServer();
|
|
36
|
+
setupAuth(app, authUserModel);
|
|
37
|
+
addAuthRoutes(app, authUserModel);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
afterEach(() => {
|
|
41
|
+
// Restore any spies installed on the shared FoodModel / Sentry.
|
|
42
|
+
(FoodModel.find as unknown as RestorableSpy).mockRestore?.();
|
|
43
|
+
(FoodModel.findById as unknown as RestorableSpy).mockRestore?.();
|
|
44
|
+
(Sentry.captureMessage as unknown as RestorableSpy).mockRestore?.();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
const mountFood = (options: Partial<ModelRouterOptions<Food>> = {}): void => {
|
|
48
|
+
app.use(
|
|
49
|
+
"/food",
|
|
50
|
+
modelRouter(FoodModel, {
|
|
51
|
+
allowAnonymous: true,
|
|
52
|
+
permissions: anyPermissions,
|
|
53
|
+
...options,
|
|
54
|
+
})
|
|
55
|
+
);
|
|
56
|
+
server = supertest(app);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
it("wraps populate failures on create in a Populate error", async () => {
|
|
60
|
+
mountFood({populatePaths: [{fields: ["email"], path: "ownerId"}]});
|
|
61
|
+
|
|
62
|
+
// Creation succeeds, but the follow-up populate query rejects.
|
|
63
|
+
const rejectingQuery = {
|
|
64
|
+
exec: () => Promise.reject(new Error("populate exploded")),
|
|
65
|
+
populate() {
|
|
66
|
+
return this;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
spyOn(FoodModel, "findById").mockReturnValue(
|
|
70
|
+
rejectingQuery as unknown as ReturnType<typeof FoodModel.findById>
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
const res = await server
|
|
74
|
+
.post("/food")
|
|
75
|
+
.send({calories: 5, name: "Broccoli", ownerId: new mongoose.Types.ObjectId()})
|
|
76
|
+
.expect(400);
|
|
77
|
+
assert.include(res.body.title, "Populate error");
|
|
78
|
+
assert.include(res.body.title, "populate exploded");
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("wraps list query failures in a List error", async () => {
|
|
82
|
+
mountFood();
|
|
83
|
+
|
|
84
|
+
const rejectingQuery = {
|
|
85
|
+
exec: () => Promise.reject(new Error("list exploded")),
|
|
86
|
+
limit() {
|
|
87
|
+
return this;
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
spyOn(FoodModel, "find").mockReturnValue(
|
|
91
|
+
rejectingQuery as unknown as ReturnType<typeof FoodModel.find>
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
const res = await server.get("/food").expect(500);
|
|
95
|
+
assert.include(res.body.title, "List error");
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it("swallows Sentry failures when warning about truncated unpaginated lists", async () => {
|
|
99
|
+
mountFood({defaultLimit: 1});
|
|
100
|
+
const ownerId = new mongoose.Types.ObjectId();
|
|
101
|
+
await FoodModel.create([
|
|
102
|
+
{calories: 1, name: "A", ownerId} as Partial<Food>,
|
|
103
|
+
{calories: 2, name: "B", ownerId} as Partial<Food>,
|
|
104
|
+
]);
|
|
105
|
+
|
|
106
|
+
const captureSpy = spyOn(Sentry, "captureMessage").mockImplementation(() => {
|
|
107
|
+
throw new Error("sentry down");
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
const res = await server.get("/food").expect(200);
|
|
111
|
+
// The extra document is sliced off so only `limit` rows are returned.
|
|
112
|
+
assert.lengthOf(res.body.data, 1);
|
|
113
|
+
assert.isTrue(res.body.more);
|
|
114
|
+
assert.isAbove(captureSpy.mock.calls.length, 0);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("wraps deleteOne failures for models without soft delete", async () => {
|
|
118
|
+
const brittleSchema = new mongoose.Schema(
|
|
119
|
+
{name: {description: "The name", type: String}},
|
|
120
|
+
{strict: "throw"}
|
|
121
|
+
);
|
|
122
|
+
brittleSchema.pre("deleteOne", {document: true, query: false}, () => {
|
|
123
|
+
throw new Error("deleteOne exploded");
|
|
124
|
+
});
|
|
125
|
+
const BrittleModel = mongoose.model(`BrittleDelete_${Date.now()}`, brittleSchema);
|
|
126
|
+
|
|
127
|
+
app.use(
|
|
128
|
+
"/brittle",
|
|
129
|
+
modelRouter(BrittleModel, {allowAnonymous: true, permissions: anyPermissions})
|
|
130
|
+
);
|
|
131
|
+
server = supertest(app);
|
|
132
|
+
|
|
133
|
+
const created = await BrittleModel.create({name: "doomed"});
|
|
134
|
+
const res = await server.delete(`/brittle/${created._id}`).expect(400);
|
|
135
|
+
assert.include(res.body.title, "deleteOne exploded");
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
it("wraps non-APIError transformer failures during array operations", async () => {
|
|
139
|
+
mountFood({
|
|
140
|
+
transformer: {
|
|
141
|
+
transform: () => {
|
|
142
|
+
throw new Error("transform exploded");
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
});
|
|
146
|
+
const food = await FoodModel.create({
|
|
147
|
+
calories: 1,
|
|
148
|
+
name: "Tagged",
|
|
149
|
+
ownerId: new mongoose.Types.ObjectId(),
|
|
150
|
+
} as Partial<Food>);
|
|
151
|
+
|
|
152
|
+
const res = await server.post(`/food/${food._id}/tags`).send({tags: "vegetable"}).expect(403);
|
|
153
|
+
assert.include(res.body.title, "transform exploded");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("wraps save failures during array operations", async () => {
|
|
157
|
+
mountFood();
|
|
158
|
+
const food = await FoodModel.create({
|
|
159
|
+
calories: 1,
|
|
160
|
+
name: "Eaten",
|
|
161
|
+
ownerId: new mongoose.Types.ObjectId(),
|
|
162
|
+
} as Partial<Food>);
|
|
163
|
+
|
|
164
|
+
// eatenBy is an ObjectId array, so pushing an unparseable id fails on save.
|
|
165
|
+
const res = await server
|
|
166
|
+
.post(`/food/${food._id}/eatenBy`)
|
|
167
|
+
.send({eatenBy: "not-an-object-id"})
|
|
168
|
+
.expect(400);
|
|
169
|
+
assert.include(res.body.title, "PATCH Pre Update error");
|
|
170
|
+
});
|
|
171
|
+
});
|
package/src/api.errors.test.ts
CHANGED
package/src/api.hooks.test.ts
CHANGED
package/src/api.query.test.ts
CHANGED
package/src/api.test.ts
CHANGED
package/src/api.ts
CHANGED
|
@@ -58,6 +58,7 @@ export interface JSONObject {
|
|
|
58
58
|
export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
|
|
59
59
|
|
|
60
60
|
export const addPopulateToQuery = (
|
|
61
|
+
// noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
61
62
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
62
63
|
builtQuery: mongoose.Query<any[], any, Record<string, never>, any>,
|
|
63
64
|
populatePaths?: PopulatePath[]
|
|
@@ -710,6 +711,7 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
710
711
|
|
|
711
712
|
if (options.populatePaths) {
|
|
712
713
|
try {
|
|
714
|
+
// noExplicitAny: mongoose Query type varies based on populatePaths
|
|
713
715
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
|
|
714
716
|
let populateQuery: any = model.findById(data._id);
|
|
715
717
|
populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
|
|
@@ -1079,6 +1081,7 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
1079
1081
|
}
|
|
1080
1082
|
|
|
1081
1083
|
if (options.populatePaths) {
|
|
1084
|
+
// noExplicitAny: mongoose Query type varies based on populatePaths
|
|
1082
1085
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
|
|
1083
1086
|
let populateQuery: any = model.findById(doc._id);
|
|
1084
1087
|
populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
|
|
@@ -1192,11 +1195,11 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
1192
1195
|
})
|
|
1193
1196
|
);
|
|
1194
1197
|
|
|
1195
|
-
async
|
|
1198
|
+
const arrayOperation = async (
|
|
1196
1199
|
req: Request,
|
|
1197
1200
|
res: Response,
|
|
1198
1201
|
operation: "POST" | "PATCH" | "DELETE"
|
|
1199
|
-
) {
|
|
1202
|
+
) => {
|
|
1200
1203
|
// TODO Combine array operations and .patch(), as they are very similar.
|
|
1201
1204
|
|
|
1202
1205
|
if (!(await checkPermissions("update", options.permissions.update, req.user))) {
|
|
@@ -1347,19 +1350,19 @@ function _buildModelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
1347
1350
|
return res.json({
|
|
1348
1351
|
data: serialize<T>(req, options, doc as unknown as Document<unknown, unknown, unknown> & T),
|
|
1349
1352
|
});
|
|
1350
|
-
}
|
|
1353
|
+
};
|
|
1351
1354
|
|
|
1352
|
-
async
|
|
1355
|
+
const arrayPost = async (req: Request, res: Response) => {
|
|
1353
1356
|
return arrayOperation(req, res, "POST");
|
|
1354
|
-
}
|
|
1357
|
+
};
|
|
1355
1358
|
|
|
1356
|
-
async
|
|
1359
|
+
const arrayPatch = async (req: Request, res: Response) => {
|
|
1357
1360
|
return arrayOperation(req, res, "PATCH");
|
|
1358
|
-
}
|
|
1361
|
+
};
|
|
1359
1362
|
|
|
1360
|
-
async
|
|
1363
|
+
const arrayDelete = async (req: Request, res: Response) => {
|
|
1361
1364
|
return arrayOperation(req, res, "DELETE");
|
|
1362
|
-
}
|
|
1365
|
+
};
|
|
1363
1366
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1364
1367
|
if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
|
|
1365
1368
|
router.post(
|
|
@@ -1439,6 +1442,7 @@ export interface AsyncHandlerOptions {
|
|
|
1439
1442
|
* }));
|
|
1440
1443
|
* ```
|
|
1441
1444
|
*/
|
|
1445
|
+
// noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
|
|
1442
1446
|
// biome-ignore lint/suspicious/noExplicitAny: handlers may have narrower Request<Params> generics — Express's overload signature uses any for the same reason
|
|
1443
1447
|
type AsyncHandlerFn = (req: any, res: Response, next: NextFunction) => Promise<unknown> | unknown;
|
|
1444
1448
|
|