@terreno/api 56.0.0-beta.0 → 57.0.0-beta.1
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/api.d.ts +3 -2
- package/dist/auth.js +21 -25
- package/dist/betterAuthSetup.d.ts +15 -1
- package/dist/betterAuthSetup.js +4 -6
- package/dist/configurationPlugin.js +2 -2
- package/dist/expressServer.js +11 -5
- package/dist/githubAuth.js +1 -4
- package/dist/plugins.d.ts +7 -6
- package/dist/plugins.js +24 -8
- package/dist/realtime/changeStreamWatcher.d.ts +1 -1
- package/dist/realtime/changeStreamWatcher.js +0 -2
- package/dist/realtime/realtimeApp.d.ts +1 -1
- package/dist/realtime/realtimeApp.js +16 -8
- package/dist/realtime/types.d.ts +14 -0
- package/dist/sync/executors.js +14 -14
- package/dist/sync/models.js +1 -1
- package/dist/sync/registry.d.ts +4 -4
- package/dist/sync/registry.js +1 -1
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/syncSeqPlugin.js +25 -29
- 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 +5 -6
- 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.errors.test.ts +32 -23
- package/src/api.ts +22 -12
- package/src/auth.test.ts +251 -1
- package/src/auth.ts +25 -23
- package/src/betterAuthSetup.ts +7 -7
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- 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/middleware.test.ts +16 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +24 -9
- package/src/openApiValidator.test.ts +41 -0
- package/src/permissions.middleware.test.ts +73 -81
- package/src/permissions.test.ts +35 -25
- package/src/plugins.test.ts +74 -29
- package/src/plugins.ts +29 -11
- package/src/populate.test.ts +25 -16
- package/src/realtime/changeStreamWatcher.ts +1 -4
- package/src/realtime/realtime.test.ts +239 -0
- package/src/realtime/realtimeApp.ts +15 -8
- package/src/realtime/realtimeAppSetup.test.ts +159 -0
- package/src/realtime/types.ts +14 -0
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/executors.ts +16 -14
- package/src/sync/models.ts +2 -1
- package/src/sync/registry.ts +6 -8
- package/src/sync/socketHandlers.ts +1 -3
- package/src/sync/syncFrontier.test.ts +2 -2
- package/src/sync/syncSeqPlugin.test.ts +446 -0
- package/src/sync/syncSeqPlugin.ts +43 -51
- package/src/tests/models.ts +8 -6
package/src/permissions.test.ts
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
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 supertest from "supertest";
|
|
6
4
|
import type TestAgent from "supertest/lib/agent";
|
|
7
5
|
|
|
8
6
|
import {modelRouter} from "./api";
|
|
9
|
-
import {
|
|
7
|
+
import {
|
|
8
|
+
type User as AuthUser,
|
|
9
|
+
type UserModel as AuthUserModel,
|
|
10
|
+
addAuthRoutes,
|
|
11
|
+
setupAuth,
|
|
12
|
+
} from "./auth";
|
|
10
13
|
import {
|
|
11
14
|
getUserOrganizationIds,
|
|
12
15
|
OrganizationQueryFilter,
|
|
@@ -32,8 +35,8 @@ describe("permissions", () => {
|
|
|
32
35
|
|
|
33
36
|
await setupTestData();
|
|
34
37
|
app = getBaseServer();
|
|
35
|
-
setupAuth(app, UserModel as
|
|
36
|
-
addAuthRoutes(app, UserModel as
|
|
38
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
39
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
37
40
|
app.use(
|
|
38
41
|
"/food",
|
|
39
42
|
modelRouter(FoodModel, {
|
|
@@ -210,10 +213,19 @@ describe("permissions", () => {
|
|
|
210
213
|
});
|
|
211
214
|
});
|
|
212
215
|
|
|
216
|
+
const testUser = (
|
|
217
|
+
overrides: Partial<AuthUser & {organizationIds?: string[]; isAnonymous?: boolean}> = {}
|
|
218
|
+
): AuthUser & {organizationIds?: string[]; isAnonymous?: boolean} => ({
|
|
219
|
+
_id: "user-123",
|
|
220
|
+
admin: false,
|
|
221
|
+
id: "user-123",
|
|
222
|
+
...overrides,
|
|
223
|
+
});
|
|
224
|
+
|
|
213
225
|
describe("permissions module", () => {
|
|
214
226
|
describe("OwnerQueryFilter", () => {
|
|
215
227
|
it("returns ownerId filter when user is provided", () => {
|
|
216
|
-
const user =
|
|
228
|
+
const user = testUser();
|
|
217
229
|
const filter = OwnerQueryFilter(user);
|
|
218
230
|
expect(filter).toEqual({ownerId: "user-123"});
|
|
219
231
|
});
|
|
@@ -226,26 +238,26 @@ describe("permissions module", () => {
|
|
|
226
238
|
|
|
227
239
|
describe("getUserOrganizationIds", () => {
|
|
228
240
|
it("returns the user's organizationIds", () => {
|
|
229
|
-
const user = {id: "u1", organizationIds: ["org-1", "org-2"]}
|
|
241
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
230
242
|
expect(getUserOrganizationIds(user)).toEqual(["org-1", "org-2"]);
|
|
231
243
|
});
|
|
232
244
|
|
|
233
245
|
it("returns an empty array when missing or undefined", () => {
|
|
234
|
-
expect(getUserOrganizationIds({id: "u1"}
|
|
246
|
+
expect(getUserOrganizationIds(testUser({id: "u1"}))).toEqual([]);
|
|
235
247
|
expect(getUserOrganizationIds(undefined)).toEqual([]);
|
|
236
248
|
});
|
|
237
249
|
});
|
|
238
250
|
|
|
239
251
|
describe("OrganizationQueryFilter", () => {
|
|
240
252
|
it("returns an $in filter over the user's organizationIds", () => {
|
|
241
|
-
const user = {id: "u1", organizationIds: ["org-1", "org-2"]}
|
|
253
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
242
254
|
expect(OrganizationQueryFilter(user)).toEqual({
|
|
243
255
|
organizationId: {$in: ["org-1", "org-2"]},
|
|
244
256
|
});
|
|
245
257
|
});
|
|
246
258
|
|
|
247
259
|
it("returns an empty $in filter when the user has no organizations", () => {
|
|
248
|
-
const user = {id: "u1"}
|
|
260
|
+
const user = testUser({id: "u1"});
|
|
249
261
|
expect(OrganizationQueryFilter(user)).toEqual({organizationId: {$in: []}});
|
|
250
262
|
});
|
|
251
263
|
|
|
@@ -256,7 +268,7 @@ describe("permissions module", () => {
|
|
|
256
268
|
|
|
257
269
|
describe("Permissions.IsOrganizationMember", () => {
|
|
258
270
|
it("returns true when no object is provided", () => {
|
|
259
|
-
const user = {id: "u1", organizationIds: ["org-1"]}
|
|
271
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
260
272
|
expect(Permissions.IsOrganizationMember("list", user, undefined)).toBe(true);
|
|
261
273
|
});
|
|
262
274
|
|
|
@@ -267,46 +279,46 @@ describe("permissions module", () => {
|
|
|
267
279
|
});
|
|
268
280
|
|
|
269
281
|
it("returns true for admins regardless of membership", () => {
|
|
270
|
-
const user = {admin: true, id: "admin-1", organizationIds: []}
|
|
282
|
+
const user = testUser({admin: true, id: "admin-1", organizationIds: []});
|
|
271
283
|
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
272
284
|
true
|
|
273
285
|
);
|
|
274
286
|
});
|
|
275
287
|
|
|
276
288
|
it("returns true when the user belongs to the document's organization", () => {
|
|
277
|
-
const user = {id: "u1", organizationIds: ["org-1", "org-2"]}
|
|
289
|
+
const user = testUser({id: "u1", organizationIds: ["org-1", "org-2"]});
|
|
278
290
|
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-2"})).toBe(
|
|
279
291
|
true
|
|
280
292
|
);
|
|
281
293
|
});
|
|
282
294
|
|
|
283
295
|
it("returns false when the user does not belong to the document's organization", () => {
|
|
284
|
-
const user = {id: "u1", organizationIds: ["org-1"]}
|
|
296
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
285
297
|
expect(Permissions.IsOrganizationMember("update", user, {organizationId: "org-9"})).toBe(
|
|
286
298
|
false
|
|
287
299
|
);
|
|
288
300
|
});
|
|
289
301
|
|
|
290
302
|
it("returns false when the document has no organizationId", () => {
|
|
291
|
-
const user = {id: "u1", organizationIds: ["org-1"]}
|
|
303
|
+
const user = testUser({id: "u1", organizationIds: ["org-1"]});
|
|
292
304
|
expect(Permissions.IsOrganizationMember("read", user, {})).toBe(false);
|
|
293
305
|
});
|
|
294
306
|
});
|
|
295
307
|
|
|
296
308
|
describe("Permissions.IsAuthenticatedOrReadOnly", () => {
|
|
297
309
|
it("returns true for authenticated non-anonymous users", () => {
|
|
298
|
-
const user = {
|
|
310
|
+
const user = testUser({isAnonymous: false});
|
|
299
311
|
expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(true);
|
|
300
312
|
});
|
|
301
313
|
|
|
302
314
|
it("returns true for read methods when user is anonymous", () => {
|
|
303
|
-
const user = {
|
|
315
|
+
const user = testUser({isAnonymous: true});
|
|
304
316
|
expect(Permissions.IsAuthenticatedOrReadOnly("list", user)).toBe(true);
|
|
305
317
|
expect(Permissions.IsAuthenticatedOrReadOnly("read", user)).toBe(true);
|
|
306
318
|
});
|
|
307
319
|
|
|
308
320
|
it("returns false for write methods when user is anonymous", () => {
|
|
309
|
-
const user = {
|
|
321
|
+
const user = testUser({isAnonymous: true});
|
|
310
322
|
expect(Permissions.IsAuthenticatedOrReadOnly("create", user)).toBe(false);
|
|
311
323
|
expect(Permissions.IsAuthenticatedOrReadOnly("update", user)).toBe(false);
|
|
312
324
|
expect(Permissions.IsAuthenticatedOrReadOnly("delete", user)).toBe(false);
|
|
@@ -315,32 +327,30 @@ describe("permissions module", () => {
|
|
|
315
327
|
|
|
316
328
|
describe("Permissions.IsOwnerOrReadOnly", () => {
|
|
317
329
|
it("returns true when no object is provided", () => {
|
|
318
|
-
expect(Permissions.IsOwnerOrReadOnly("update",
|
|
319
|
-
true
|
|
320
|
-
);
|
|
330
|
+
expect(Permissions.IsOwnerOrReadOnly("update", testUser(), undefined)).toBe(true);
|
|
321
331
|
});
|
|
322
332
|
|
|
323
333
|
it("returns true for admin users", () => {
|
|
324
|
-
const user = {admin: true, id: "admin-123"}
|
|
334
|
+
const user = testUser({admin: true, id: "admin-123"});
|
|
325
335
|
const obj = {ownerId: "other-user"};
|
|
326
336
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
|
|
327
337
|
});
|
|
328
338
|
|
|
329
339
|
it("returns true when user is owner", () => {
|
|
330
|
-
const user =
|
|
340
|
+
const user = testUser();
|
|
331
341
|
const obj = {ownerId: "user-123"};
|
|
332
342
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(true);
|
|
333
343
|
});
|
|
334
344
|
|
|
335
345
|
it("returns true for read methods when not owner", () => {
|
|
336
|
-
const user =
|
|
346
|
+
const user = testUser();
|
|
337
347
|
const obj = {ownerId: "other-user"};
|
|
338
348
|
expect(Permissions.IsOwnerOrReadOnly("list", user, obj)).toBe(true);
|
|
339
349
|
expect(Permissions.IsOwnerOrReadOnly("read", user, obj)).toBe(true);
|
|
340
350
|
});
|
|
341
351
|
|
|
342
352
|
it("returns false for write methods when not owner", () => {
|
|
343
|
-
const user =
|
|
353
|
+
const user = testUser();
|
|
344
354
|
const obj = {ownerId: "other-user"};
|
|
345
355
|
expect(Permissions.IsOwnerOrReadOnly("update", user, obj)).toBe(false);
|
|
346
356
|
expect(Permissions.IsOwnerOrReadOnly("delete", user, obj)).toBe(false);
|
package/src/plugins.test.ts
CHANGED
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
// noExplicitAny: test mock typing
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
|
|
3
1
|
import {beforeEach, describe, expect, it, setSystemTime} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
4
3
|
import type express from "express";
|
|
5
|
-
import {
|
|
4
|
+
import {
|
|
5
|
+
type DateSchemaDefinition,
|
|
6
|
+
type Document,
|
|
7
|
+
type HydratedDocument,
|
|
8
|
+
type Model,
|
|
9
|
+
model,
|
|
10
|
+
Schema,
|
|
11
|
+
} from "mongoose";
|
|
6
12
|
import supertest from "supertest";
|
|
7
13
|
import type TestAgent from "supertest/lib/agent";
|
|
8
14
|
import {modelRouter} from "./api";
|
|
9
|
-
import {addAuthRoutes, setupAuth} from "./auth";
|
|
15
|
+
import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "./auth";
|
|
10
16
|
import {type APIErrorConstructor, InternalServerError, isAPIError, NotFoundError} from "./errors";
|
|
11
17
|
import {Permissions} from "./permissions";
|
|
12
18
|
import {
|
|
@@ -36,17 +42,31 @@ interface Stuff extends IsDeleted {
|
|
|
36
42
|
|
|
37
43
|
interface StuffModelType extends Model<Stuff> {
|
|
38
44
|
findOneOrNone(
|
|
39
|
-
query: Record<string,
|
|
45
|
+
query: Record<string, unknown>,
|
|
40
46
|
errorArgs?: Partial<APIErrorConstructor>
|
|
41
47
|
): Promise<(Document & Stuff) | null>;
|
|
42
48
|
findExactlyOne(
|
|
43
|
-
query: Record<string,
|
|
49
|
+
query: Record<string, unknown>,
|
|
44
50
|
errorArgs?: Partial<APIErrorConstructor>
|
|
45
51
|
): Promise<Document & Stuff>;
|
|
52
|
+
upsert(
|
|
53
|
+
conditions: Record<string, unknown>,
|
|
54
|
+
update: Record<string, unknown>
|
|
55
|
+
): Promise<Document & Stuff>;
|
|
46
56
|
}
|
|
47
57
|
|
|
58
|
+
const expectApiError = (error: unknown) => {
|
|
59
|
+
if (!isAPIError(error)) {
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
return error;
|
|
63
|
+
};
|
|
64
|
+
|
|
48
65
|
const stuffSchema = new Schema<Stuff>({
|
|
49
|
-
date: {
|
|
66
|
+
date: {
|
|
67
|
+
description: "The date associated with this item",
|
|
68
|
+
type: DateOnly as unknown as DateSchemaDefinition,
|
|
69
|
+
},
|
|
50
70
|
name: {description: "The name of the item", type: String},
|
|
51
71
|
ownerId: {description: "The user who owns this item", type: String},
|
|
52
72
|
});
|
|
@@ -62,7 +82,7 @@ const StuffModel = model<Stuff>("Stuff", stuffSchema) as unknown as StuffModelTy
|
|
|
62
82
|
describe("baseUserPlugin", () => {
|
|
63
83
|
it("adds admin and email fields to the schema", () => {
|
|
64
84
|
const testSchema = new Schema({});
|
|
65
|
-
baseUserPlugin(testSchema
|
|
85
|
+
baseUserPlugin(testSchema);
|
|
66
86
|
|
|
67
87
|
const adminPath = testSchema.path("admin");
|
|
68
88
|
expect(adminPath).toBeDefined();
|
|
@@ -141,7 +161,7 @@ describe("isDeleted", () => {
|
|
|
141
161
|
});
|
|
142
162
|
|
|
143
163
|
describe("findOneOrNone", () => {
|
|
144
|
-
let things:
|
|
164
|
+
let things: HydratedDocument<Stuff>;
|
|
145
165
|
|
|
146
166
|
beforeEach(async () => {
|
|
147
167
|
await StuffModel.deleteMany({});
|
|
@@ -182,8 +202,8 @@ describe("findOneOrNone", () => {
|
|
|
182
202
|
await fn();
|
|
183
203
|
// If the promise doesn't reject, the test should fail
|
|
184
204
|
throw new Error("Expected promise to reject");
|
|
185
|
-
} catch (
|
|
186
|
-
|
|
205
|
+
} catch (caught: unknown) {
|
|
206
|
+
const error = expectApiError(caught);
|
|
187
207
|
expect(error.title).toBe("Oh no!");
|
|
188
208
|
expect(error.status).toBe(400);
|
|
189
209
|
expect(error.detail).toBe(
|
|
@@ -214,7 +234,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
214
234
|
});
|
|
215
235
|
|
|
216
236
|
describe("when the schema has the findOneOrNone plugin", () => {
|
|
217
|
-
let things:
|
|
237
|
+
let things: HydratedDocument<Stuff>;
|
|
218
238
|
|
|
219
239
|
beforeEach(async () => {
|
|
220
240
|
[things] = await Promise.all([
|
|
@@ -246,7 +266,8 @@ describe("findOneOrNoneFor", () => {
|
|
|
246
266
|
try {
|
|
247
267
|
await fn();
|
|
248
268
|
throw new Error("Expected promise to reject");
|
|
249
|
-
} catch (
|
|
269
|
+
} catch (caught: unknown) {
|
|
270
|
+
const error = expectApiError(caught);
|
|
250
271
|
expect(error.title).toBe("Oh no!");
|
|
251
272
|
expect(error.status).toBe(400);
|
|
252
273
|
}
|
|
@@ -254,7 +275,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
254
275
|
});
|
|
255
276
|
|
|
256
277
|
describe("when the schema does NOT have the findOneOrNone plugin", () => {
|
|
257
|
-
let bareThings:
|
|
278
|
+
let bareThings: HydratedDocument<BareThing>;
|
|
258
279
|
|
|
259
280
|
beforeEach(async () => {
|
|
260
281
|
[bareThings] = await Promise.all([
|
|
@@ -271,7 +292,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
271
292
|
it("returns a single match", async () => {
|
|
272
293
|
const result = await findOneOrNoneFor(BareThingModel, {name: "Things"});
|
|
273
294
|
expect(result).not.toBeNull();
|
|
274
|
-
expect(
|
|
295
|
+
expect(result?._id?.toString()).toBe(bareThings._id?.toString());
|
|
275
296
|
});
|
|
276
297
|
|
|
277
298
|
it("throws when multiple documents match", async () => {
|
|
@@ -286,7 +307,8 @@ describe("findOneOrNoneFor", () => {
|
|
|
286
307
|
try {
|
|
287
308
|
await fn();
|
|
288
309
|
throw new Error("Expected promise to reject");
|
|
289
|
-
} catch (
|
|
310
|
+
} catch (caught: unknown) {
|
|
311
|
+
const error = expectApiError(caught);
|
|
290
312
|
expect(error.title).toBe("Oh no!");
|
|
291
313
|
expect(error.status).toBe(400);
|
|
292
314
|
}
|
|
@@ -295,7 +317,7 @@ describe("findOneOrNoneFor", () => {
|
|
|
295
317
|
});
|
|
296
318
|
|
|
297
319
|
describe("findExactlyOne", () => {
|
|
298
|
-
let things:
|
|
320
|
+
let things: HydratedDocument<Stuff>;
|
|
299
321
|
|
|
300
322
|
beforeEach(async () => {
|
|
301
323
|
await StuffModel.deleteMany({});
|
|
@@ -353,8 +375,8 @@ describe("findExactlyOne", () => {
|
|
|
353
375
|
await fn();
|
|
354
376
|
// If the promise doesn't reject, the test should fail
|
|
355
377
|
throw new Error("Expected promise to reject");
|
|
356
|
-
} catch (
|
|
357
|
-
|
|
378
|
+
} catch (caught: unknown) {
|
|
379
|
+
const error = expectApiError(caught);
|
|
358
380
|
expect(error.title).toBe("Oh no!");
|
|
359
381
|
expect(error.status).toBe(400);
|
|
360
382
|
expect(error.detail).toBe(
|
|
@@ -372,7 +394,7 @@ describe("upsertPlugin", () => {
|
|
|
372
394
|
});
|
|
373
395
|
|
|
374
396
|
it("creates a new document when none exists", async () => {
|
|
375
|
-
const result = await
|
|
397
|
+
const result = await StuffModel.upsert({name: "NewThing"}, {ownerId: "456"});
|
|
376
398
|
expect(result.name).toBe("NewThing");
|
|
377
399
|
expect(result.ownerId).toBe("456");
|
|
378
400
|
|
|
@@ -387,7 +409,7 @@ describe("upsertPlugin", () => {
|
|
|
387
409
|
ownerId: "123",
|
|
388
410
|
});
|
|
389
411
|
|
|
390
|
-
const result = await
|
|
412
|
+
const result = await StuffModel.upsert({name: "ExistingThing"}, {ownerId: "789"});
|
|
391
413
|
|
|
392
414
|
expect(result._id.toString()).toBe(initial._id.toString());
|
|
393
415
|
expect(result.ownerId).toBe("789");
|
|
@@ -403,7 +425,7 @@ describe("upsertPlugin", () => {
|
|
|
403
425
|
StuffModel.create({name: "Thing2", ownerId: "123"}),
|
|
404
426
|
]);
|
|
405
427
|
|
|
406
|
-
const fn = () =>
|
|
428
|
+
const fn = () => StuffModel.upsert({ownerId: "123"}, {name: "Updated"});
|
|
407
429
|
await expect(fn()).rejects.toThrow(/^upsert find query returned multiple documents$/);
|
|
408
430
|
try {
|
|
409
431
|
await fn();
|
|
@@ -420,7 +442,7 @@ describe("upsertPlugin", () => {
|
|
|
420
442
|
});
|
|
421
443
|
|
|
422
444
|
it("combines conditions and update data for new documents", async () => {
|
|
423
|
-
const result = await
|
|
445
|
+
const result = await StuffModel.upsert({name: "TestCondition"}, {ownerId: "999"});
|
|
424
446
|
|
|
425
447
|
expect(result.name).toBe("TestCondition");
|
|
426
448
|
expect(result.ownerId).toBe("999");
|
|
@@ -460,6 +482,16 @@ describe("excludeArchivedPlugin", () => {
|
|
|
460
482
|
expect(results[0].name).toBe("Active");
|
|
461
483
|
});
|
|
462
484
|
|
|
485
|
+
it("excludes archived documents from findOne() by default", async () => {
|
|
486
|
+
await ArchivableModel.create({archived: false, name: "Active"});
|
|
487
|
+
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
488
|
+
|
|
489
|
+
const active = await ArchivableModel.findOne({name: "Active"});
|
|
490
|
+
expect(active?.name).toBe("Active");
|
|
491
|
+
const archived = await ArchivableModel.findOne({name: "Archived"});
|
|
492
|
+
expect(archived).toBeNull();
|
|
493
|
+
});
|
|
494
|
+
|
|
463
495
|
it("includes archived documents when explicitly requested", async () => {
|
|
464
496
|
await ArchivableModel.create({archived: false, name: "Active"});
|
|
465
497
|
await ArchivableModel.create({archived: true, name: "Archived"});
|
|
@@ -480,7 +512,7 @@ describe("excludeArchivedPlugin", () => {
|
|
|
480
512
|
});
|
|
481
513
|
|
|
482
514
|
describe("TypeScript return types", () => {
|
|
483
|
-
let _things:
|
|
515
|
+
let _things: HydratedDocument<Stuff>;
|
|
484
516
|
|
|
485
517
|
beforeEach(async () => {
|
|
486
518
|
await StuffModel.deleteMany({});
|
|
@@ -523,15 +555,28 @@ describe("TypeScript return types", () => {
|
|
|
523
555
|
});
|
|
524
556
|
});
|
|
525
557
|
describe("DateOnly", () => {
|
|
558
|
+
it("strips the time portion when getting a Date value", () => {
|
|
559
|
+
const dateOnly = new DateOnly("date", {});
|
|
560
|
+
const value = dateOnly.get(new Date("2005-10-10T17:17:17.017Z")) as unknown as Date;
|
|
561
|
+
assert.instanceOf(value, Date);
|
|
562
|
+
assert.equal(value.toISOString(), "2005-10-10T00:00:00.000Z");
|
|
563
|
+
});
|
|
564
|
+
|
|
565
|
+
it("returns non-Date values unchanged when getting a value", () => {
|
|
566
|
+
const dateOnly = new DateOnly("date", {});
|
|
567
|
+
assert.isNull(dateOnly.get(null));
|
|
568
|
+
assert.equal(dateOnly.get("2005-10-10") as unknown as string, "2005-10-10");
|
|
569
|
+
});
|
|
570
|
+
|
|
526
571
|
it("throws error with invalid date", async () => {
|
|
527
572
|
try {
|
|
528
573
|
await StuffModel.create({
|
|
529
|
-
date: "foo" as
|
|
574
|
+
date: "foo" as unknown as Date,
|
|
530
575
|
name: "Things",
|
|
531
576
|
ownerId: "123",
|
|
532
577
|
});
|
|
533
|
-
} catch (error:
|
|
534
|
-
expect(error.message).toMatch(/Cast to DateOnly failed/);
|
|
578
|
+
} catch (error: unknown) {
|
|
579
|
+
expect((error as Error).message).toMatch(/Cast to DateOnly failed/);
|
|
535
580
|
return;
|
|
536
581
|
}
|
|
537
582
|
throw new Error("Expected error was not thrown");
|
|
@@ -575,8 +620,8 @@ describe("DateOnly", () => {
|
|
|
575
620
|
beforeEach(async () => {
|
|
576
621
|
await setupDb();
|
|
577
622
|
app = getBaseServer();
|
|
578
|
-
setupAuth(app, UserModel as
|
|
579
|
-
addAuthRoutes(app, UserModel as
|
|
623
|
+
setupAuth(app, UserModel as unknown as AuthUserModel);
|
|
624
|
+
addAuthRoutes(app, UserModel as unknown as AuthUserModel);
|
|
580
625
|
app.use(
|
|
581
626
|
"/stuff",
|
|
582
627
|
modelRouter(StuffModel, {
|
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
|
}
|
|
@@ -291,10 +292,10 @@ export interface IsArchived {
|
|
|
291
292
|
}
|
|
292
293
|
|
|
293
294
|
/**
|
|
294
|
-
* Adds an `archived` boolean field and excludes archived documents from `find()`
|
|
295
|
-
* default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
|
|
296
|
-
* {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
|
|
297
|
-
* (and still directly queryable) rather than treated as deleted.
|
|
295
|
+
* Adds an `archived` boolean field and excludes archived documents from `find()` / `findOne()`
|
|
296
|
+
* queries by default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
|
|
297
|
+
* analog to {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
|
|
298
|
+
* but kept (and still directly queryable) rather than treated as deleted.
|
|
298
299
|
* @param schema Mongoose Schema
|
|
299
300
|
* @param defaultValue Default value for the `archived` field (defaults to `false`)
|
|
300
301
|
*/
|
|
@@ -315,15 +316,28 @@ export const excludeArchivedPlugin = (
|
|
|
315
316
|
},
|
|
316
317
|
});
|
|
317
318
|
|
|
319
|
+
// Mirror isDeletedPlugin: filter both find and findOne so findExactlyOne / findOneOrNone
|
|
320
|
+
// also exclude archived documents unless the query sets `archived` explicitly.
|
|
318
321
|
// noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
319
322
|
// biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
320
|
-
|
|
321
|
-
const conditions =
|
|
323
|
+
const applyArchiveFilter = (query: Query<any, any>): void => {
|
|
324
|
+
const conditions = query.getFilter();
|
|
322
325
|
// Only apply the default filter when the query does not mention `archived` at all, so an
|
|
323
326
|
// explicit `{archived: true}` (or `false`) is always respected.
|
|
324
327
|
if (conditions.archived === undefined) {
|
|
325
|
-
|
|
328
|
+
query.setQuery({...conditions, archived: {$ne: true}});
|
|
326
329
|
}
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
// noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
333
|
+
// biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
334
|
+
schema.pre<Query<any, any>>("find", function () {
|
|
335
|
+
applyArchiveFilter(this);
|
|
336
|
+
});
|
|
337
|
+
// noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
338
|
+
// biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
|
|
339
|
+
schema.pre<Query<any, any>>("findOne", function () {
|
|
340
|
+
applyArchiveFilter(this);
|
|
327
341
|
});
|
|
328
342
|
};
|
|
329
343
|
|
|
@@ -372,7 +386,11 @@ export class DateOnly extends SchemaType {
|
|
|
372
386
|
const handler = this.$conditionalHandlers[$conditional];
|
|
373
387
|
|
|
374
388
|
if (!handler) {
|
|
375
|
-
throw new
|
|
389
|
+
throw new APIError({
|
|
390
|
+
detail: `Can't use ${$conditional} with DateOnly.`,
|
|
391
|
+
status: 400,
|
|
392
|
+
title: "Unsupported query conditional for DateOnly",
|
|
393
|
+
});
|
|
376
394
|
}
|
|
377
395
|
|
|
378
396
|
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
|
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
// noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
2
|
-
// biome-ignore-all lint/suspicious/noExplicitAny: change stream and socket handlers use dynamic document shapes
|
|
3
|
-
|
|
4
1
|
import * as Sentry from "@sentry/bun";
|
|
5
2
|
import type express from "express";
|
|
6
3
|
import {DateTime} from "luxon";
|
|
@@ -195,7 +192,7 @@ const getSocketsInRoom = (io: Server, room: string): RealtimeSocketWithAuth[] =>
|
|
|
195
192
|
*/
|
|
196
193
|
export interface AuthorizedEmitEntry {
|
|
197
194
|
modelName: string;
|
|
198
|
-
options: {permissions: {read: PermissionMethod<
|
|
195
|
+
options: {permissions: {read: PermissionMethod<unknown>[]}};
|
|
199
196
|
}
|
|
200
197
|
|
|
201
198
|
const canReadDocument = async (
|