@terreno/api 0.30.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 -122
- package/LICENSE +21 -202
- package/dist/actions.openApi.test.js +1 -3
- package/dist/actions.test.js +0 -2
- package/dist/api.coverage.test.js +0 -2
- package/dist/api.d.ts +3 -2
- package/dist/api.errorPaths.test.js +86 -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/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/openApiBuilder.test.js +0 -2
- package/dist/openApiValidator.test.js +34 -0
- package/dist/plugins.d.ts +3 -2
- package/dist/plugins.js +5 -1
- package/dist/plugins.test.js +12 -0
- 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/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 +19 -12
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +7 -9
- package/src/api.errorPaths.test.ts +47 -1
- package/src/api.ts +22 -11
- package/src/betterAuthSetup.ts +7 -7
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/expressServer.ts +11 -5
- package/src/githubAuth.ts +1 -3
- 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 +14 -0
- package/src/plugins.ts +9 -4
- package/src/populate.test.ts +25 -16
- 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/tests/models.ts +8 -6
package/src/api.ts
CHANGED
|
@@ -54,6 +54,10 @@ import {
|
|
|
54
54
|
} from "./transformers";
|
|
55
55
|
import {isValidObjectId} from "./utils";
|
|
56
56
|
|
|
57
|
+
// noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
|
|
58
|
+
// biome-ignore lint/suspicious/noExplicitAny: Framework routers accept consumer models with arbitrary query helpers, methods, virtuals, and hydrated document types
|
|
59
|
+
type ModelLike<T> = Model<T, any, any, any, any, any>;
|
|
60
|
+
|
|
57
61
|
export type JSONPrimitive = string | number | boolean | null;
|
|
58
62
|
export interface JSONArray extends Array<JSONValue> {}
|
|
59
63
|
export interface JSONObject {
|
|
@@ -403,7 +407,7 @@ const parseDateRangeBound = (rawValue: unknown, queryKey: string): Date => {
|
|
|
403
407
|
* so admin changelist date-range filters map to valid Mongoose range queries.
|
|
404
408
|
*/
|
|
405
409
|
const mergeDateRangeQueryParams = <T>(
|
|
406
|
-
model:
|
|
410
|
+
model: ModelLike<T>,
|
|
407
411
|
query: Record<string, unknown>
|
|
408
412
|
): Record<string, unknown> => {
|
|
409
413
|
const schema = model.schema;
|
|
@@ -526,7 +530,7 @@ const shouldValidate = <T>(
|
|
|
526
530
|
|
|
527
531
|
// Get body validation middleware if validation is enabled
|
|
528
532
|
const getBodyValidationMiddleware = <T>(
|
|
529
|
-
model:
|
|
533
|
+
model: ModelLike<T>,
|
|
530
534
|
options: ModelRouterOptions<T>,
|
|
531
535
|
operation: "create" | "update"
|
|
532
536
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
@@ -556,7 +560,7 @@ const getBodyValidationMiddleware = <T>(
|
|
|
556
560
|
|
|
557
561
|
// Get query validation middleware if validation is enabled
|
|
558
562
|
const getQueryValidationMiddleware = <T>(
|
|
559
|
-
model:
|
|
563
|
+
model: ModelLike<T>,
|
|
560
564
|
options: ModelRouterOptions<T>
|
|
561
565
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
562
566
|
const querySchema = buildQuerySchemaFromFields(model, options.queryFields);
|
|
@@ -607,22 +611,22 @@ export interface ModelRouterRegistration {
|
|
|
607
611
|
*/
|
|
608
612
|
export function modelRouter<T>(
|
|
609
613
|
path: string,
|
|
610
|
-
model:
|
|
614
|
+
model: ModelLike<T>,
|
|
611
615
|
options: ModelRouterOptions<T>
|
|
612
616
|
): ModelRouterRegistration;
|
|
613
|
-
export function modelRouter<T>(model:
|
|
617
|
+
export function modelRouter<T>(model: ModelLike<T>, options: ModelRouterOptions<T>): express.Router;
|
|
614
618
|
export function modelRouter<T>(
|
|
615
|
-
pathOrModel: string |
|
|
616
|
-
modelOrOptions:
|
|
619
|
+
pathOrModel: string | ModelLike<T>,
|
|
620
|
+
modelOrOptions: ModelLike<T> | ModelRouterOptions<T>,
|
|
617
621
|
maybeOptions?: ModelRouterOptions<T>
|
|
618
622
|
): express.Router | ModelRouterRegistration {
|
|
619
|
-
let model:
|
|
623
|
+
let model: ModelLike<T>;
|
|
620
624
|
let options: ModelRouterOptions<T>;
|
|
621
625
|
let path: string | undefined;
|
|
622
626
|
|
|
623
627
|
if (typeof pathOrModel === "string") {
|
|
624
628
|
path = pathOrModel;
|
|
625
|
-
model = modelOrOptions as
|
|
629
|
+
model = modelOrOptions as ModelLike<T>;
|
|
626
630
|
options = maybeOptions as ModelRouterOptions<T>;
|
|
627
631
|
} else {
|
|
628
632
|
model = pathOrModel;
|
|
@@ -661,7 +665,10 @@ export function modelRouter<T>(
|
|
|
661
665
|
return router;
|
|
662
666
|
}
|
|
663
667
|
|
|
664
|
-
const _buildModelRouter = <T>(
|
|
668
|
+
const _buildModelRouter = <T>(
|
|
669
|
+
model: ModelLike<T>,
|
|
670
|
+
options: ModelRouterOptions<T>
|
|
671
|
+
): express.Router => {
|
|
665
672
|
const router = express.Router();
|
|
666
673
|
|
|
667
674
|
assertNoActionCollisions(model, options);
|
|
@@ -1389,7 +1396,11 @@ const _buildModelRouter = <T>(model: Model<T>, options: ModelRouterOptions<T>):
|
|
|
1389
1396
|
return arrayOperation(req, res, "DELETE");
|
|
1390
1397
|
};
|
|
1391
1398
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1392
|
-
if (
|
|
1399
|
+
if (
|
|
1400
|
+
(Object.values(model.schema.paths) as mongoose.SchemaType[]).find(
|
|
1401
|
+
(config) => config.instance === "Array"
|
|
1402
|
+
)
|
|
1403
|
+
) {
|
|
1393
1404
|
router.post(
|
|
1394
1405
|
"/:id/:field",
|
|
1395
1406
|
authenticateMiddleware(options.allowAnonymous),
|
package/src/betterAuthSetup.ts
CHANGED
|
@@ -173,6 +173,7 @@ export const createBetterAuthSessionMiddleware = (
|
|
|
173
173
|
// Loose shape used when mutating Mongoose user documents during Better Auth sync.
|
|
174
174
|
// The fields are added by the consumer's user schema (via baseUserPlugin or similar).
|
|
175
175
|
interface MutableUserDoc {
|
|
176
|
+
admin?: boolean;
|
|
176
177
|
email?: string;
|
|
177
178
|
name?: string;
|
|
178
179
|
betterAuthId?: string;
|
|
@@ -185,9 +186,7 @@ export const syncBetterAuthUser = async (
|
|
|
185
186
|
userModel: UserModel,
|
|
186
187
|
betterAuthUser: BetterAuthUser,
|
|
187
188
|
oauthProvider?: string
|
|
188
|
-
|
|
189
|
-
// biome-ignore lint/suspicious/noExplicitAny: return is a consumer-defined user document; tests inspect varied fields
|
|
190
|
-
): Promise<any> => {
|
|
189
|
+
): Promise<MutableUserDoc> => {
|
|
191
190
|
try {
|
|
192
191
|
const existingUser = (await findOneOrNoneFor(userModel, {
|
|
193
192
|
betterAuthId: betterAuthUser.id,
|
|
@@ -219,16 +218,17 @@ export const syncBetterAuthUser = async (
|
|
|
219
218
|
|
|
220
219
|
// Use Better Auth ID as _id when it's a valid ObjectId (MongoDB adapter) so frontend IDs match
|
|
221
220
|
const useAsId = mongoose.isValidObjectId(betterAuthUser.id) ? {_id: betterAuthUser.id} : {};
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
221
|
+
const UserDocumentConstructor = userModel as unknown as new (
|
|
222
|
+
doc: Record<string, unknown>
|
|
223
|
+
) => MutableUserDoc;
|
|
224
|
+
const newUser = new UserDocumentConstructor({
|
|
225
225
|
...useAsId,
|
|
226
226
|
admin: false,
|
|
227
227
|
betterAuthId: betterAuthUser.id,
|
|
228
228
|
email: betterAuthUser.email,
|
|
229
229
|
name: betterAuthUser.name || betterAuthUser.email.split("@")[0],
|
|
230
230
|
oauthProvider: oauthProvider || null,
|
|
231
|
-
})
|
|
231
|
+
});
|
|
232
232
|
await newUser.save();
|
|
233
233
|
logger.info(`Created new user from Better Auth: ${newUser.id}`);
|
|
234
234
|
return newUser;
|
|
@@ -344,7 +344,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
|
|
|
344
344
|
const updated = await this.findOneAndUpdate(
|
|
345
345
|
singletonFilter,
|
|
346
346
|
{$set: setFields},
|
|
347
|
-
{
|
|
347
|
+
{returnDocument: "after", runValidators: true}
|
|
348
348
|
);
|
|
349
349
|
if (updated) {
|
|
350
350
|
return updated;
|
|
@@ -356,7 +356,7 @@ export const configurationPlugin = (schema: Schema, options?: ConfigurationPlugi
|
|
|
356
356
|
return this.findOneAndUpdate(
|
|
357
357
|
singletonFilter,
|
|
358
358
|
{$set: setFields},
|
|
359
|
-
{
|
|
359
|
+
{returnDocument: "after", runValidators: true}
|
|
360
360
|
).orFail();
|
|
361
361
|
};
|
|
362
362
|
|
package/src/consentApp.test.ts
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {afterEach, beforeEach, describe, expect, it} from "bun:test";
|
|
4
2
|
import type express from "express";
|
|
3
|
+
import type {HydratedDocument} from "mongoose";
|
|
5
4
|
import supertest from "supertest";
|
|
6
5
|
import type TestAgent from "supertest/lib/agent";
|
|
7
|
-
import {
|
|
6
|
+
import type {UserModel as UserMongooseModel} from "./auth";
|
|
7
|
+
import {ConsentApp, type ConsentAppOptions} from "./consentApp";
|
|
8
8
|
import {ConsentForm} from "./models/consentForm";
|
|
9
9
|
import {ConsentResponse} from "./models/consentResponse";
|
|
10
10
|
import {TerrenoApp} from "./terrenoApp";
|
|
11
|
-
import {authAsUser, setupDb, UserModel} from "./tests";
|
|
11
|
+
import {authAsUser, setupDb, type User, UserModel} from "./tests";
|
|
12
|
+
import type {ConsentFormDocument} from "./types/consentForm";
|
|
12
13
|
|
|
13
|
-
const buildApp = (consentAppOptions = {}): express.Application =>
|
|
14
|
+
const buildApp = (consentAppOptions: ConsentAppOptions = {}): express.Application =>
|
|
14
15
|
new TerrenoApp({
|
|
15
16
|
skipListen: true,
|
|
16
|
-
userModel: UserModel as
|
|
17
|
+
userModel: UserModel as unknown as UserMongooseModel,
|
|
17
18
|
})
|
|
18
19
|
.register(new ConsentApp(consentAppOptions))
|
|
19
20
|
.build();
|
|
20
21
|
|
|
21
22
|
describe("ConsentApp", () => {
|
|
22
|
-
let admin:
|
|
23
|
-
let notAdmin:
|
|
23
|
+
let admin: HydratedDocument<User>;
|
|
24
|
+
let notAdmin: HydratedDocument<User>;
|
|
24
25
|
let adminAgent: TestAgent;
|
|
25
26
|
let userAgent: TestAgent;
|
|
26
27
|
|
|
@@ -344,8 +345,7 @@ describe("ConsentApp", () => {
|
|
|
344
345
|
|
|
345
346
|
// Build app with resolver that only returns privacy forms
|
|
346
347
|
const filteredApp = buildApp({
|
|
347
|
-
resolveConsentForms: (_user
|
|
348
|
-
forms.filter((f) => f.type === "privacy"),
|
|
348
|
+
resolveConsentForms: (_user, forms) => forms.filter((f) => f.type === "privacy"),
|
|
349
349
|
});
|
|
350
350
|
const filteredAgent = await authAsUser(filteredApp, "notAdmin");
|
|
351
351
|
|
|
@@ -367,7 +367,7 @@ describe("ConsentApp", () => {
|
|
|
367
367
|
|
|
368
368
|
// Build app with resolver that skips admin users
|
|
369
369
|
const filteredApp = buildApp({
|
|
370
|
-
resolveConsentForms: (user
|
|
370
|
+
resolveConsentForms: (user, forms) => (user.admin ? [] : forms),
|
|
371
371
|
});
|
|
372
372
|
const filteredAdmin = await authAsUser(filteredApp, "admin");
|
|
373
373
|
const filteredUser = await authAsUser(filteredApp, "notAdmin");
|
|
@@ -388,7 +388,7 @@ describe("ConsentApp", () => {
|
|
|
388
388
|
});
|
|
389
389
|
|
|
390
390
|
describe("POST /consents/respond", () => {
|
|
391
|
-
let form:
|
|
391
|
+
let form: ConsentFormDocument;
|
|
392
392
|
|
|
393
393
|
beforeEach(async () => {
|
|
394
394
|
form = await ConsentForm.create({
|
package/src/expressServer.ts
CHANGED
|
@@ -7,6 +7,7 @@ import cloneDeep from "lodash/cloneDeep";
|
|
|
7
7
|
import onFinished from "on-finished";
|
|
8
8
|
import passport from "passport";
|
|
9
9
|
import type {ModelRouterOptions} from "./api";
|
|
10
|
+
import {APIError} from "./errors";
|
|
10
11
|
import {type LoggingOptions, logger} from "./logger";
|
|
11
12
|
import {sendToSlack} from "./notifiers/slackNotifier";
|
|
12
13
|
|
|
@@ -16,16 +17,16 @@ const IS_JEST = process.env.JEST_WORKER_ID !== undefined;
|
|
|
16
17
|
|
|
17
18
|
export const setupEnvironment = (): void => {
|
|
18
19
|
if (!process.env.TOKEN_ISSUER) {
|
|
19
|
-
throw new
|
|
20
|
+
throw new APIError({status: 500, title: "TOKEN_ISSUER must be set in env."});
|
|
20
21
|
}
|
|
21
22
|
if (!process.env.TOKEN_SECRET) {
|
|
22
|
-
throw new
|
|
23
|
+
throw new APIError({status: 500, title: "TOKEN_SECRET must be set."});
|
|
23
24
|
}
|
|
24
25
|
if (!process.env.REFRESH_TOKEN_SECRET) {
|
|
25
|
-
throw new
|
|
26
|
+
throw new APIError({status: 500, title: "REFRESH_TOKEN_SECRET must be set."});
|
|
26
27
|
}
|
|
27
28
|
if (!process.env.SESSION_SECRET) {
|
|
28
|
-
throw new
|
|
29
|
+
throw new APIError({status: 500, title: "SESSION_SECRET must be set."});
|
|
29
30
|
}
|
|
30
31
|
if (!process.env.TOKEN_EXPIRES_IN && !IS_JEST) {
|
|
31
32
|
logger.warn("TOKEN_EXPIRES_IN is not set so using default.");
|
|
@@ -190,7 +191,12 @@ export const cronjob = (
|
|
|
190
191
|
try {
|
|
191
192
|
new cron.CronJob(cronSchedule, callback, null, true, "America/Chicago");
|
|
192
193
|
} catch (error) {
|
|
193
|
-
throw new
|
|
194
|
+
throw new APIError({
|
|
195
|
+
cause: error,
|
|
196
|
+
detail: `Failed to create cronjob ${name} with schedule ${cronSchedule}: ${error}`,
|
|
197
|
+
status: 500,
|
|
198
|
+
title: "Failed to create cronjob",
|
|
199
|
+
});
|
|
194
200
|
}
|
|
195
201
|
};
|
|
196
202
|
|
package/src/githubAuth.ts
CHANGED
|
@@ -90,9 +90,7 @@ export const setupGitHubAuth = (
|
|
|
90
90
|
|
|
91
91
|
passport.use(
|
|
92
92
|
"github",
|
|
93
|
-
|
|
94
|
-
// biome-ignore lint/suspicious/noExplicitAny: passport-github2's typed constructor overloads don't match passReqToCallback variant
|
|
95
|
-
new (GitHubStrategy as any)(
|
|
93
|
+
new GitHubStrategy(
|
|
96
94
|
{
|
|
97
95
|
callbackURL: githubOptions.callbackURL,
|
|
98
96
|
clientID: githubOptions.clientId,
|
|
@@ -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,6 +1,7 @@
|
|
|
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";
|
|
@@ -469,6 +470,19 @@ describe("TypeScript return types", () => {
|
|
|
469
470
|
});
|
|
470
471
|
});
|
|
471
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
|
+
|
|
472
486
|
it("throws error with invalid date", async () => {
|
|
473
487
|
try {
|
|
474
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,
|
|
@@ -11,6 +10,8 @@ import mongoose, {
|
|
|
11
10
|
|
|
12
11
|
import {APIError, type APIErrorOptions, InternalServerError, NotFoundError} from "./errors";
|
|
13
12
|
|
|
13
|
+
export type ModelQuery<T> = Partial<Record<keyof T, unknown>> & Record<string, unknown>;
|
|
14
|
+
|
|
14
15
|
export interface BaseUser {
|
|
15
16
|
admin: boolean;
|
|
16
17
|
email: string;
|
|
@@ -172,14 +173,14 @@ export const findOneOrNone = <T>(schema: Schema<T>): void => {
|
|
|
172
173
|
*/
|
|
173
174
|
export const findOneOrNoneFor = async <T>(
|
|
174
175
|
model: mongoose.Model<T>,
|
|
175
|
-
query:
|
|
176
|
+
query: ModelQuery<T>,
|
|
176
177
|
errorArgs?: Partial<APIErrorOptions>
|
|
177
178
|
): Promise<(Document & T) | null> => {
|
|
178
179
|
const withStatic = model as mongoose.Model<T> & Partial<FindOneOrNonePlugin<T>>;
|
|
179
180
|
if (typeof withStatic.findOneOrNone === "function") {
|
|
180
181
|
return withStatic.findOneOrNone(query, errorArgs);
|
|
181
182
|
}
|
|
182
|
-
const results = await model.find(query);
|
|
183
|
+
const results = await model.find(query as never);
|
|
183
184
|
if (results.length === 0) {
|
|
184
185
|
return null;
|
|
185
186
|
}
|
|
@@ -329,7 +330,11 @@ export class DateOnly extends SchemaType {
|
|
|
329
330
|
const handler = this.$conditionalHandlers[$conditional];
|
|
330
331
|
|
|
331
332
|
if (!handler) {
|
|
332
|
-
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
|
+
});
|
|
333
338
|
}
|
|
334
339
|
|
|
335
340
|
return handler.call(this, val);
|
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
|