@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.
- package/CHANGELOG.md +2 -43
- package/LICENSE +21 -202
- package/dist/actions.js +17 -8
- package/dist/actions.openApi.test.js +1 -3
- package/dist/actions.test.js +8 -5
- package/dist/api.arrayOperations.test.js +16 -8
- package/dist/api.coverage.test.js +2 -3
- package/dist/api.d.ts +3 -2
- package/dist/api.errorPaths.test.js +608 -1
- package/dist/api.errors.test.js +9 -0
- package/dist/api.js +137 -170
- package/dist/api.query.test.js +20 -8
- package/dist/api.test.js +12 -6
- package/dist/auth.coverage.test.d.ts +1 -0
- package/dist/auth.coverage.test.js +202 -0
- package/dist/auth.test.js +159 -0
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/consentApp.test.js +1 -5
- package/dist/docLoader.js +5 -1
- package/dist/envConfigurationPlugin.d.ts +1 -1
- package/dist/envConfigurationPlugin.js +0 -2
- package/dist/errors.d.ts +14 -0
- package/dist/errors.js +24 -2
- package/dist/errors.test.js +137 -0
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/httpClient.js +5 -1
- package/dist/openApiBuilder.test.js +0 -2
- package/dist/openApiValidator.test.js +34 -0
- package/dist/plugins.d.ts +6 -5
- package/dist/plugins.js +56 -10
- package/dist/plugins.test.js +73 -17
- package/dist/populate.test.js +9 -12
- package/dist/realtime/realtime.test.js +231 -0
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +6 -2
- package/dist/realtime/realtimeAppSetup.test.d.ts +1 -0
- package/dist/realtime/realtimeAppSetup.test.js +213 -0
- package/dist/realtime/registry.d.ts +3 -2
- package/dist/tests/models.d.ts +27 -11
- package/dist/tests/models.js +5 -3
- package/dist/tests/testHelper.d.ts +9 -3
- package/package.json +4 -5
- package/src/actions.openApi.test.ts +7 -10
- package/src/actions.test.ts +27 -15
- package/src/actions.ts +21 -12
- package/src/api.arrayOperations.test.ts +16 -8
- package/src/api.coverage.test.ts +9 -10
- package/src/api.errorPaths.test.ts +360 -4
- package/src/api.errors.test.ts +12 -0
- package/src/api.query.test.ts +20 -8
- package/src/api.test.ts +12 -6
- package/src/api.ts +162 -171
- package/src/auth.coverage.test.ts +101 -0
- package/src/auth.test.ts +125 -2
- package/src/betterAuthSetup.ts +7 -7
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +6 -2
- package/src/envConfigurationPlugin.ts +2 -6
- package/src/errors.test.ts +106 -1
- package/src/errors.ts +25 -1
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- package/src/httpClient.ts +6 -2
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/plugins.test.ts +59 -9
- package/src/plugins.ts +81 -39
- package/src/populate.test.ts +25 -16
- package/src/realtime/changeStreamWatcher.ts +8 -1
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +8 -5
- package/src/realtime/realtimeAppSetup.test.ts +161 -0
- package/src/realtime/registry.ts +3 -4
- package/src/tests/models.ts +8 -6
|
@@ -79,7 +79,7 @@ const versionConfigSchema = new mongoose.Schema<VersionConfigDocument, VersionCo
|
|
|
79
79
|
// Enforce singleton: only one VersionConfig document can exist.
|
|
80
80
|
// The _singleton field is always "config" (required, immutable, enum-constrained)
|
|
81
81
|
// and a unique index guarantees at most one document.
|
|
82
|
-
(versionConfigSchema as mongoose.Schema).add({
|
|
82
|
+
(versionConfigSchema as unknown as mongoose.Schema).add({
|
|
83
83
|
_singleton: {
|
|
84
84
|
default: "config",
|
|
85
85
|
description: "Sentinel field to enforce singleton via unique index",
|
|
@@ -1,5 +1,3 @@
|
|
|
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
3
|
import type {Router} from "express";
|
|
@@ -7,12 +5,25 @@ import supertest from "supertest";
|
|
|
7
5
|
import type TestAgent from "supertest/lib/agent";
|
|
8
6
|
|
|
9
7
|
import {type ModelRouterOptions, modelRouter} from "./api";
|
|
8
|
+
import type {UserModel as AuthUserModel} from "./auth";
|
|
10
9
|
import {createOpenApiBuilder, OpenApiMiddlewareBuilder} from "./openApiBuilder";
|
|
11
10
|
import {Permissions} from "./permissions";
|
|
12
11
|
import {TerrenoApp} from "./terrenoApp";
|
|
13
|
-
import {FoodModel, UserModel} from "./tests";
|
|
12
|
+
import {type Food, FoodModel, UserModel} from "./tests";
|
|
13
|
+
|
|
14
|
+
/** The subset of an OpenAPI parameter object the assertions below inspect. */
|
|
15
|
+
interface OpenApiParameter {
|
|
16
|
+
name: string;
|
|
17
|
+
in: string;
|
|
18
|
+
required?: boolean;
|
|
19
|
+
description?: string;
|
|
20
|
+
schema: {type: string};
|
|
21
|
+
}
|
|
14
22
|
|
|
15
|
-
function addRoutesWithBuilder(
|
|
23
|
+
function addRoutesWithBuilder(
|
|
24
|
+
router: Router,
|
|
25
|
+
options?: Partial<ModelRouterOptions<unknown>>
|
|
26
|
+
): void {
|
|
16
27
|
// Add a custom endpoint using the OpenApiMiddlewareBuilder
|
|
17
28
|
const statsMiddleware = createOpenApiBuilder(options ?? {})
|
|
18
29
|
.withTags(["Stats"])
|
|
@@ -124,8 +135,8 @@ function addRoutesWithBuilder(router: Router, options?: Partial<ModelRouterOptio
|
|
|
124
135
|
// Standard modelRouter for food
|
|
125
136
|
router.use(
|
|
126
137
|
"/food",
|
|
127
|
-
modelRouter(FoodModel
|
|
128
|
-
...options,
|
|
138
|
+
modelRouter(FoodModel, {
|
|
139
|
+
...(options as Partial<ModelRouterOptions<Food>>),
|
|
129
140
|
allowAnonymous: true,
|
|
130
141
|
permissions: {
|
|
131
142
|
create: [Permissions.IsAny],
|
|
@@ -149,7 +160,7 @@ describe("OpenApiMiddlewareBuilder", () => {
|
|
|
149
160
|
app = new TerrenoApp({
|
|
150
161
|
configureApp: addRoutesWithBuilder,
|
|
151
162
|
skipListen: true,
|
|
152
|
-
userModel: UserModel as
|
|
163
|
+
userModel: UserModel as unknown as AuthUserModel,
|
|
153
164
|
}).build();
|
|
154
165
|
});
|
|
155
166
|
|
|
@@ -189,7 +200,9 @@ describe("OpenApiMiddlewareBuilder", () => {
|
|
|
189
200
|
expect(statsPath.get.description).toBe("Returns aggregated statistics about food items");
|
|
190
201
|
|
|
191
202
|
// Check query parameter
|
|
192
|
-
const categoryParam = statsPath.get.parameters.find(
|
|
203
|
+
const categoryParam = statsPath.get.parameters.find(
|
|
204
|
+
(p: OpenApiParameter) => p.name === "category"
|
|
205
|
+
);
|
|
193
206
|
expect(categoryParam).toBeDefined();
|
|
194
207
|
expect(categoryParam.in).toBe("query");
|
|
195
208
|
expect(categoryParam.schema.type).toBe("string");
|
|
@@ -269,7 +282,9 @@ describe("OpenApiMiddlewareBuilder", () => {
|
|
|
269
282
|
const categoryPath = res.body.paths["/food/categories/{categoryId}"];
|
|
270
283
|
expect(categoryPath).toBeDefined();
|
|
271
284
|
|
|
272
|
-
const pathParam = categoryPath.get.parameters.find(
|
|
285
|
+
const pathParam = categoryPath.get.parameters.find(
|
|
286
|
+
(p: OpenApiParameter) => p.name === "categoryId"
|
|
287
|
+
);
|
|
273
288
|
expect(pathParam).toBeDefined();
|
|
274
289
|
expect(pathParam.in).toBe("path");
|
|
275
290
|
expect(pathParam.required).toBe(true);
|
|
@@ -563,6 +563,47 @@ describe("openApiValidator", () => {
|
|
|
563
563
|
expect(req.query.page).toBe(5);
|
|
564
564
|
});
|
|
565
565
|
|
|
566
|
+
it("runs only body validation when no query schema is provided", () => {
|
|
567
|
+
configureOpenApiValidator({coerceTypes: true});
|
|
568
|
+
|
|
569
|
+
const middleware = createValidator({
|
|
570
|
+
body: {count: {type: "number"}, name: {required: true, type: "string"}},
|
|
571
|
+
});
|
|
572
|
+
|
|
573
|
+
const req = {
|
|
574
|
+
body: {count: "3", name: "ok"},
|
|
575
|
+
method: "POST",
|
|
576
|
+
path: "/test",
|
|
577
|
+
query: {unchecked: "kept"},
|
|
578
|
+
} as unknown as Request;
|
|
579
|
+
const res = {} as Response;
|
|
580
|
+
|
|
581
|
+
const nextCalls: unknown[][] = [];
|
|
582
|
+
middleware(req, res, ((...args: unknown[]) => {
|
|
583
|
+
nextCalls.push(args);
|
|
584
|
+
}) as NextFunction);
|
|
585
|
+
|
|
586
|
+
expect(nextCalls).toEqual([[]]);
|
|
587
|
+
expect(req.body.count).toBe(3);
|
|
588
|
+
// Query params are untouched when no query schema is configured.
|
|
589
|
+
expect(req.query.unchecked).toBe("kept");
|
|
590
|
+
});
|
|
591
|
+
|
|
592
|
+
it("throws body validation errors when only a body schema is provided", () => {
|
|
593
|
+
configureOpenApiValidator({});
|
|
594
|
+
|
|
595
|
+
const middleware = createValidator({
|
|
596
|
+
body: {name: {required: true, type: "string"}},
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
const req = {body: {}, method: "POST", path: "/test", query: {}} as unknown as Request;
|
|
600
|
+
const res = {} as Response;
|
|
601
|
+
|
|
602
|
+
expect(() => middleware(req, res, (() => {}) as NextFunction)).toThrow(
|
|
603
|
+
"Request validation failed"
|
|
604
|
+
);
|
|
605
|
+
});
|
|
606
|
+
|
|
566
607
|
it("propagates body validation error via next", () => {
|
|
567
608
|
let capturedErrors: ErrorObject[] = [];
|
|
568
609
|
configureOpenApiValidator({
|
package/src/plugins.test.ts
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
// noExplicitAny: test mock typing
|
|
2
2
|
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
3
|
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
4
|
+
import {assert} from "chai";
|
|
4
5
|
import type express from "express";
|
|
5
6
|
import {type Document, type Model, model, Schema} from "mongoose";
|
|
6
7
|
import supertest from "supertest";
|
|
7
8
|
import type TestAgent from "supertest/lib/agent";
|
|
8
9
|
import {modelRouter} from "./api";
|
|
9
10
|
import {addAuthRoutes, setupAuth} from "./auth";
|
|
10
|
-
import type
|
|
11
|
+
import {type APIErrorConstructor, InternalServerError, isAPIError, NotFoundError} from "./errors";
|
|
11
12
|
import {Permissions} from "./permissions";
|
|
12
13
|
import {
|
|
13
14
|
baseUserPlugin,
|
|
@@ -170,7 +171,7 @@ describe("findOneOrNone", () => {
|
|
|
170
171
|
|
|
171
172
|
it("throws error with two matches.", async () => {
|
|
172
173
|
const fn = () => StuffModel.findOneOrNone({ownerId: "123"});
|
|
173
|
-
await expect(fn()).rejects.toThrow(
|
|
174
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
174
175
|
});
|
|
175
176
|
|
|
176
177
|
it("throws custom error with two matches.", async () => {
|
|
@@ -184,7 +185,10 @@ describe("findOneOrNone", () => {
|
|
|
184
185
|
// Check if the error has title and status properties
|
|
185
186
|
expect(error.title).toBe("Oh no!");
|
|
186
187
|
expect(error.status).toBe(400);
|
|
187
|
-
expect(error.detail).toBe(
|
|
188
|
+
expect(error.detail).toBe(
|
|
189
|
+
'Stuff.findOne query returned multiple documents. query: {"ownerId":"123"}'
|
|
190
|
+
);
|
|
191
|
+
expect(error.code).toBe("find-one-multiple-documents");
|
|
188
192
|
}
|
|
189
193
|
});
|
|
190
194
|
});
|
|
@@ -231,7 +235,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
231
235
|
|
|
232
236
|
it("throws when multiple documents match", async () => {
|
|
233
237
|
const fn = () => findOneOrNoneFor(StuffModel, {ownerId: "123"});
|
|
234
|
-
await expect(fn()).rejects.toThrow(
|
|
238
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
235
239
|
});
|
|
236
240
|
|
|
237
241
|
it("forwards errorArgs to the thrown APIError", async () => {
|
|
@@ -271,7 +275,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
271
275
|
|
|
272
276
|
it("throws when multiple documents match", async () => {
|
|
273
277
|
const fn = () => findOneOrNoneFor(BareThingModel, {ownerId: "123"});
|
|
274
|
-
await expect(fn()).rejects.toThrow(
|
|
278
|
+
await expect(fn()).rejects.toThrow(/^findOne query returned multiple documents$/);
|
|
275
279
|
});
|
|
276
280
|
|
|
277
281
|
it("forwards errorArgs to the thrown APIError", async () => {
|
|
@@ -310,7 +314,25 @@ describe("findExactlyOne", () => {
|
|
|
310
314
|
|
|
311
315
|
it("throws error with no matches.", async () => {
|
|
312
316
|
const fn = () => StuffModel.findExactlyOne({name: "OtherStuff"});
|
|
313
|
-
await expect(fn()).rejects.toThrow(
|
|
317
|
+
await expect(fn()).rejects.toThrow(/^findExactlyOne query returned no documents$/);
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("throws a NotFoundError carrying the model name in detail and meta", async () => {
|
|
321
|
+
try {
|
|
322
|
+
await StuffModel.findExactlyOne({name: "OtherStuff"});
|
|
323
|
+
throw new Error("Expected promise to reject");
|
|
324
|
+
} catch (error: unknown) {
|
|
325
|
+
expect(error).toBeInstanceOf(NotFoundError);
|
|
326
|
+
if (!isAPIError(error)) {
|
|
327
|
+
throw error;
|
|
328
|
+
}
|
|
329
|
+
expect(error.status).toBe(404);
|
|
330
|
+
expect(error.code).toBe("find-exactly-one-no-documents");
|
|
331
|
+
expect(error.detail).toBe(
|
|
332
|
+
'Stuff.findExactlyOne query returned no documents. query: {"name":"OtherStuff"}'
|
|
333
|
+
);
|
|
334
|
+
expect(error.meta).toEqual({model: "Stuff"});
|
|
335
|
+
}
|
|
314
336
|
});
|
|
315
337
|
|
|
316
338
|
it("returns a single match", async () => {
|
|
@@ -320,7 +342,7 @@ describe("findExactlyOne", () => {
|
|
|
320
342
|
|
|
321
343
|
it("throws error with two matches.", async () => {
|
|
322
344
|
const fn = () => StuffModel.findExactlyOne({ownerId: "123"});
|
|
323
|
-
await expect(fn()).rejects.toThrow(
|
|
345
|
+
await expect(fn()).rejects.toThrow(/^findExactlyOne query returned multiple documents$/);
|
|
324
346
|
});
|
|
325
347
|
|
|
326
348
|
it("throws custom error with two matches.", async () => {
|
|
@@ -334,7 +356,10 @@ describe("findExactlyOne", () => {
|
|
|
334
356
|
// Check if the error has title and status properties
|
|
335
357
|
expect(error.title).toBe("Oh no!");
|
|
336
358
|
expect(error.status).toBe(400);
|
|
337
|
-
expect(error.detail).toBe(
|
|
359
|
+
expect(error.detail).toBe(
|
|
360
|
+
'Stuff.findExactlyOne query returned multiple documents. query: {"ownerId":"123"}'
|
|
361
|
+
);
|
|
362
|
+
expect(error.code).toBe("find-exactly-one-multiple-documents");
|
|
338
363
|
}
|
|
339
364
|
});
|
|
340
365
|
});
|
|
@@ -378,7 +403,19 @@ describe("upsertPlugin", () => {
|
|
|
378
403
|
]);
|
|
379
404
|
|
|
380
405
|
const fn = () => (StuffModel as any).upsert({ownerId: "123"}, {name: "Updated"});
|
|
381
|
-
await expect(fn()).rejects.toThrow(
|
|
406
|
+
await expect(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/);
|
|
407
|
+
try {
|
|
408
|
+
await fn();
|
|
409
|
+
} catch (error: unknown) {
|
|
410
|
+
expect(error).toBeInstanceOf(InternalServerError);
|
|
411
|
+
if (!isAPIError(error)) {
|
|
412
|
+
throw error;
|
|
413
|
+
}
|
|
414
|
+
expect(error.code).toBe("upsert-multiple-documents");
|
|
415
|
+
expect(error.detail).toBe(
|
|
416
|
+
'Stuff.upsert find query returned multiple documents. query: {"ownerId":"123"}'
|
|
417
|
+
);
|
|
418
|
+
}
|
|
382
419
|
});
|
|
383
420
|
|
|
384
421
|
it("combines conditions and update data for new documents", async () => {
|
|
@@ -433,6 +470,19 @@ describe("TypeScript return types", () => {
|
|
|
433
470
|
});
|
|
434
471
|
});
|
|
435
472
|
describe("DateOnly", () => {
|
|
473
|
+
it("strips the time portion when getting a Date value", () => {
|
|
474
|
+
const dateOnly = new DateOnly("date", {});
|
|
475
|
+
const value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z")) as unknown as Date;
|
|
476
|
+
assert.instanceOf(value, Date);
|
|
477
|
+
assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
it("returns non-Date values unchanged when getting a value", () => {
|
|
481
|
+
const dateOnly = new DateOnly("date", {});
|
|
482
|
+
assert.isNull(dateOnly.get(null));
|
|
483
|
+
assert.equal(dateOnly.get("2005-10-10") as unknown as string, "2005-10-10");
|
|
484
|
+
});
|
|
485
|
+
|
|
436
486
|
it("throws error with invalid date", async () => {
|
|
437
487
|
try {
|
|
438
488
|
await StuffModel.create({
|
package/src/plugins.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import {DateTime} from "luxon";
|
|
2
2
|
import mongoose, {
|
|
3
3
|
type Document,
|
|
4
|
-
type FilterQuery,
|
|
5
4
|
Error as MongooseError,
|
|
6
5
|
type Query,
|
|
7
6
|
type Schema,
|
|
@@ -9,13 +8,31 @@ import mongoose, {
|
|
|
9
8
|
type SchemaTypeOptions,
|
|
10
9
|
} from "mongoose";
|
|
11
10
|
|
|
12
|
-
import {APIError, type
|
|
11
|
+
import {APIError, type APIErrorOptions, InternalServerError, NotFoundError} from "./errors";
|
|
12
|
+
|
|
13
|
+
export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
|
|
13
14
|
|
|
14
15
|
export interface BaseUser {
|
|
15
16
|
admin: boolean;
|
|
16
17
|
email: string;
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Builds the error thrown by the query plugins. `errorArgs` is applied last so consumers can
|
|
22
|
+
* override every field, including `status`; the status-specific subclass is used when the resulting
|
|
23
|
+
* status still matches one of them, so Sentry sees a meaningful error type.
|
|
24
|
+
*/
|
|
25
|
+
const pluginError = (defaults: APIErrorOptions, errorArgs?: Partial<APIErrorOptions>): APIError => {
|
|
26
|
+
const options: APIErrorOptions = {...defaults, ...errorArgs};
|
|
27
|
+
if (options.status === 404) {
|
|
28
|
+
return new NotFoundError(options);
|
|
29
|
+
}
|
|
30
|
+
if (options.status === 500) {
|
|
31
|
+
return new InternalServerError(options);
|
|
32
|
+
}
|
|
33
|
+
return new APIError(options);
|
|
34
|
+
};
|
|
35
|
+
|
|
19
36
|
// noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
20
37
|
// biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
|
|
21
38
|
export const baseUserPlugin = (schema: Schema<any, any, any, any>): void => {
|
|
@@ -122,19 +139,23 @@ export const firebaseJWTPlugin = (schema: Schema): void => {
|
|
|
122
139
|
export const findOneOrNone = <T>(schema: Schema<T>): void => {
|
|
123
140
|
schema.statics.findOneOrNone = async function (
|
|
124
141
|
query: Record<string, unknown>,
|
|
125
|
-
errorArgs?: Partial<
|
|
142
|
+
errorArgs?: Partial<APIErrorOptions>
|
|
126
143
|
): Promise<(Document & T) | null> {
|
|
127
144
|
const results = await this.find(query);
|
|
128
145
|
if (results.length === 0) {
|
|
129
146
|
return null;
|
|
130
147
|
}
|
|
131
148
|
if (results.length > 1) {
|
|
132
|
-
throw
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
149
|
+
throw pluginError(
|
|
150
|
+
{
|
|
151
|
+
code: "find-one-multiple-documents",
|
|
152
|
+
detail: `${this.modelName}.findOne query returned multiple documents. query: ${JSON.stringify(query)}`,
|
|
153
|
+
meta: {model: this.modelName},
|
|
154
|
+
status: 500,
|
|
155
|
+
title: "findOne query returned multiple documents",
|
|
156
|
+
},
|
|
157
|
+
errorArgs
|
|
158
|
+
);
|
|
138
159
|
}
|
|
139
160
|
return results[0];
|
|
140
161
|
};
|
|
@@ -152,24 +173,28 @@ export const findOneOrNone = <T>(schema: Schema<T>): void => {
|
|
|
152
173
|
*/
|
|
153
174
|
export const findOneOrNoneFor = async <T>(
|
|
154
175
|
model: mongoose.Model<T>,
|
|
155
|
-
query:
|
|
156
|
-
errorArgs?: Partial<
|
|
176
|
+
query: ModelQuery<T>,
|
|
177
|
+
errorArgs?: Partial<APIErrorOptions>
|
|
157
178
|
): Promise<(Document & T) | null> => {
|
|
158
179
|
const withStatic = model as mongoose.Model<T> & Partial<FindOneOrNonePlugin<T>>;
|
|
159
180
|
if (typeof withStatic.findOneOrNone === "function") {
|
|
160
181
|
return withStatic.findOneOrNone(query, errorArgs);
|
|
161
182
|
}
|
|
162
|
-
const results = await model.find(query);
|
|
183
|
+
const results = await model.find(query as never);
|
|
163
184
|
if (results.length === 0) {
|
|
164
185
|
return null;
|
|
165
186
|
}
|
|
166
187
|
if (results.length > 1) {
|
|
167
|
-
throw
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
188
|
+
throw pluginError(
|
|
189
|
+
{
|
|
190
|
+
code: "find-one-multiple-documents",
|
|
191
|
+
detail: `${model.modelName}.findOne query returned multiple documents. query: ${JSON.stringify(query)}`,
|
|
192
|
+
meta: {model: model.modelName},
|
|
193
|
+
status: 500,
|
|
194
|
+
title: "findOne query returned multiple documents",
|
|
195
|
+
},
|
|
196
|
+
errorArgs
|
|
197
|
+
);
|
|
173
198
|
}
|
|
174
199
|
return results[0] as unknown as Document & T;
|
|
175
200
|
};
|
|
@@ -185,24 +210,32 @@ export const findOneOrNoneFor = async <T>(
|
|
|
185
210
|
export const findExactlyOne = <T>(schema: Schema<T>): void => {
|
|
186
211
|
schema.statics.findExactlyOne = async function (
|
|
187
212
|
query: Record<string, unknown>,
|
|
188
|
-
errorArgs?: Partial<
|
|
213
|
+
errorArgs?: Partial<APIErrorOptions>
|
|
189
214
|
): Promise<Document & T> {
|
|
190
215
|
const results = await this.find(query);
|
|
191
216
|
if (results.length === 0) {
|
|
192
|
-
throw
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
217
|
+
throw pluginError(
|
|
218
|
+
{
|
|
219
|
+
code: "find-exactly-one-no-documents",
|
|
220
|
+
detail: `${this.modelName}.findExactlyOne query returned no documents. query: ${JSON.stringify(query)}`,
|
|
221
|
+
meta: {model: this.modelName},
|
|
222
|
+
status: 404,
|
|
223
|
+
title: "findExactlyOne query returned no documents",
|
|
224
|
+
},
|
|
225
|
+
errorArgs
|
|
226
|
+
);
|
|
198
227
|
}
|
|
199
228
|
if (results.length > 1) {
|
|
200
|
-
throw
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
229
|
+
throw pluginError(
|
|
230
|
+
{
|
|
231
|
+
code: "find-exactly-one-multiple-documents",
|
|
232
|
+
detail: `${this.modelName}.findExactlyOne query returned multiple documents. query: ${JSON.stringify(query)}`,
|
|
233
|
+
meta: {model: this.modelName},
|
|
234
|
+
status: 500,
|
|
235
|
+
title: "findExactlyOne query returned multiple documents",
|
|
236
|
+
},
|
|
237
|
+
errorArgs
|
|
238
|
+
);
|
|
206
239
|
}
|
|
207
240
|
return results[0];
|
|
208
241
|
};
|
|
@@ -225,10 +258,11 @@ export const upsertPlugin = <T>(schema: Schema<any, any, any, any>): void => {
|
|
|
225
258
|
// Try to find the document with the given conditions.
|
|
226
259
|
const docs = await this.find(conditions);
|
|
227
260
|
if (docs.length > 1) {
|
|
228
|
-
throw new
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
261
|
+
throw new InternalServerError({
|
|
262
|
+
code: "upsert-multiple-documents",
|
|
263
|
+
detail: `${this.modelName}.upsert find query returned multiple documents. query: ${JSON.stringify(conditions)}`,
|
|
264
|
+
meta: {model: this.modelName},
|
|
265
|
+
title: "upsert find query returned multiple documents",
|
|
232
266
|
});
|
|
233
267
|
}
|
|
234
268
|
const doc = docs[0];
|
|
@@ -254,14 +288,14 @@ export interface HasUpsert<T> {
|
|
|
254
288
|
export interface FindOneOrNonePlugin<T> {
|
|
255
289
|
findOneOrNone(
|
|
256
290
|
query: Record<string, unknown>,
|
|
257
|
-
errorArgs?: Partial<
|
|
291
|
+
errorArgs?: Partial<APIErrorOptions>
|
|
258
292
|
): Promise<(Document & T) | null>;
|
|
259
293
|
}
|
|
260
294
|
|
|
261
295
|
export interface FindExactlyOnePlugin<T> {
|
|
262
296
|
findExactlyOne(
|
|
263
297
|
query: Record<string, unknown>,
|
|
264
|
-
errorArgs?: Partial<
|
|
298
|
+
errorArgs?: Partial<APIErrorOptions>
|
|
265
299
|
): Promise<Document & T>;
|
|
266
300
|
}
|
|
267
301
|
|
|
@@ -296,7 +330,11 @@ export class DateOnly extends SchemaType {
|
|
|
296
330
|
const handler = this.$conditionalHandlers[$conditional];
|
|
297
331
|
|
|
298
332
|
if (!handler) {
|
|
299
|
-
throw new
|
|
333
|
+
throw new APIError({
|
|
334
|
+
detail: `Can't use ${$conditional} with DateOnly.`,
|
|
335
|
+
status: 400,
|
|
336
|
+
title: "Unsupported query conditional for DateOnly",
|
|
337
|
+
});
|
|
300
338
|
}
|
|
301
339
|
|
|
302
340
|
return handler.call(this, val);
|
|
@@ -318,7 +356,11 @@ export class DateOnly extends SchemaType {
|
|
|
318
356
|
return date.toJSDate();
|
|
319
357
|
}
|
|
320
358
|
if (typeof val === "string" || typeof val === "number") {
|
|
321
|
-
const date =
|
|
359
|
+
const date = (
|
|
360
|
+
typeof val === "number" ? DateTime.fromMillis(val) : DateTime.fromISO(val, {zone: "utc"})
|
|
361
|
+
)
|
|
362
|
+
.toUTC()
|
|
363
|
+
.startOf("day");
|
|
322
364
|
if (!date.isValid) {
|
|
323
365
|
throw new MongooseError.CastError(
|
|
324
366
|
"DateOnly",
|
package/src/populate.test.ts
CHANGED
|
@@ -1,17 +1,24 @@
|
|
|
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 mongoose, {type Document, type HydratedDocument, Schema} from "mongoose";
|
|
5
3
|
|
|
6
4
|
import {fixMixedFields, getOpenApiSpecForModel, unpopulate} from "./populate";
|
|
7
|
-
import {FoodModel, setupTestData, type User, UserModel} from "./tests";
|
|
5
|
+
import {type Food, FoodModel, setupTestData, type User, UserModel} from "./tests";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* A Food document whose ObjectId references have been replaced by populated user
|
|
9
|
+
* documents. `unpopulate` swaps them back to ObjectIds in place, so both shapes
|
|
10
|
+
* are optional on the reference fields.
|
|
11
|
+
*/
|
|
12
|
+
type PopulatedFood = Omit<HydratedDocument<Food>, "eatenBy" | "likesIds" | "ownerId"> & {
|
|
13
|
+
ownerId: Partial<User> & {toString(): string};
|
|
14
|
+
eatenBy: (Partial<User> & {id?: string})[] & {toString(): string};
|
|
15
|
+
likesIds: {likes: boolean; userId: Partial<User> & {id?: string; toString(): string}}[];
|
|
16
|
+
};
|
|
8
17
|
|
|
9
18
|
describe("populate functions", () => {
|
|
10
19
|
let admin: HydratedDocument<User>;
|
|
11
20
|
let notAdmin: HydratedDocument<User>;
|
|
12
|
-
|
|
13
|
-
// noExplicitAny: typing as HydratedDocument<Food> causes cascading errors on populated field access patterns (e.g. populated.ownerId.name)
|
|
14
|
-
let spinach: any;
|
|
21
|
+
let spinach: HydratedDocument<Food>;
|
|
15
22
|
|
|
16
23
|
beforeEach(async () => {
|
|
17
24
|
const testData = await setupTestData();
|
|
@@ -21,9 +28,10 @@ describe("populate functions", () => {
|
|
|
21
28
|
});
|
|
22
29
|
|
|
23
30
|
it("unpopulate", async () => {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
31
|
+
await spinach.populate("ownerId");
|
|
32
|
+
await spinach.populate("eatenBy");
|
|
33
|
+
await spinach.populate("likesIds.userId");
|
|
34
|
+
const populated = spinach as unknown as PopulatedFood;
|
|
27
35
|
expect(populated.ownerId.name).toBe("Not Admin");
|
|
28
36
|
expect(populated.eatenBy[0].id).toBe(admin.id);
|
|
29
37
|
expect(populated.eatenBy[0].name).toBe("Admin");
|
|
@@ -32,9 +40,11 @@ describe("populate functions", () => {
|
|
|
32
40
|
expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
|
|
33
41
|
expect(populated.likesIds[1].userId.name).toBe("Not Admin");
|
|
34
42
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
43
|
+
const unpopulated = unpopulate(
|
|
44
|
+
populated as unknown as Document<unknown>,
|
|
45
|
+
"ownerId"
|
|
46
|
+
) as unknown as PopulatedFood;
|
|
47
|
+
expect(populated.ownerId.name).toBeUndefined();
|
|
38
48
|
expect(unpopulated.ownerId.toString()).toBe(notAdmin.id);
|
|
39
49
|
// Ensure nothing else was touched.
|
|
40
50
|
expect(populated.likesIds[0].userId.id).toBe(admin.id);
|
|
@@ -42,11 +52,11 @@ describe("populate functions", () => {
|
|
|
42
52
|
expect(populated.likesIds[1].userId.id).toBe(notAdmin.id);
|
|
43
53
|
expect(populated.likesIds[1].userId.name).toBe("Not Admin");
|
|
44
54
|
|
|
45
|
-
|
|
55
|
+
unpopulate(populated as unknown as Document<unknown>, "eatenBy");
|
|
46
56
|
expect(populated.eatenBy.toString()).toBe(admin.id);
|
|
47
57
|
expect(populated.eatenBy[0]?.name).toBeUndefined();
|
|
48
58
|
|
|
49
|
-
|
|
59
|
+
unpopulate(populated as unknown as Document<unknown>, "likesIds.userId");
|
|
50
60
|
expect(populated.likesIds[0].userId.toString()).toBe(admin.id);
|
|
51
61
|
expect(populated.likesIds[0].userId?.name).toBeUndefined();
|
|
52
62
|
expect(populated.likesIds[1].userId.toString()).toBe(notAdmin.id);
|
|
@@ -326,8 +336,7 @@ describe("filterKeys (via getOpenApiSpecForModel populatePaths)", () => {
|
|
|
326
336
|
populatePaths: [{fields: ["__proto__.polluted"], path: "ownerId"}],
|
|
327
337
|
});
|
|
328
338
|
expect(result.properties).toBeDefined();
|
|
329
|
-
|
|
330
|
-
expect((Object.prototype as any).polluted).toBeUndefined();
|
|
339
|
+
expect((Object.prototype as Record<string, unknown>).polluted).toBeUndefined();
|
|
331
340
|
const ownerProps = (result.properties.ownerId as Record<string, unknown>).properties as Record<
|
|
332
341
|
string,
|
|
333
342
|
unknown
|
|
@@ -196,7 +196,14 @@ export const serializeDoc = async (
|
|
|
196
196
|
const restMethod = method === "delete" ? "read" : method;
|
|
197
197
|
// Synthesize the minimal request shape responseHandlers commonly inspect.
|
|
198
198
|
const syntheticReq = {params: {}, query: {}, user} as unknown as express.Request;
|
|
199
|
-
return ensureApiId(
|
|
199
|
+
return ensureApiId(
|
|
200
|
+
await responseHandler(
|
|
201
|
+
doc as unknown as mongoose.Document<unknown, unknown, unknown>,
|
|
202
|
+
restMethod,
|
|
203
|
+
syntheticReq,
|
|
204
|
+
entry.options
|
|
205
|
+
)
|
|
206
|
+
);
|
|
200
207
|
} catch (error) {
|
|
201
208
|
logger.error(
|
|
202
209
|
`[realtime] modelRouter responseHandler threw during realtime serialization for ` +
|