@terreno/api 0.31.0 → 56.0.0-beta.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 +122 -2
- package/LICENSE +202 -21
- package/dist/api.d.ts +12 -3
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +100 -1
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.d.ts +1 -15
- package/dist/betterAuthSetup.js +29 -8
- package/dist/configurationPlugin.js +2 -2
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/expressServer.js +5 -11
- package/dist/githubAuth.js +4 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +15 -3
- package/dist/plugins.js +36 -6
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +3 -1
- package/dist/realtime/realtimeApp.js +75 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +40 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +903 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/tests/models.d.ts +11 -27
- package/dist/tests/models.js +3 -5
- package/dist/tests/testHelper.d.ts +3 -9
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +10 -8
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/actions.test.ts +12 -19
- package/src/actions.ts +2 -2
- package/src/api.coverage.test.ts +9 -7
- package/src/api.errorPaths.test.ts +1 -47
- package/src/api.test.ts +12 -0
- package/src/api.ts +98 -317
- package/src/auth.test.ts +128 -176
- package/src/auth.ts +109 -0
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +27 -8
- package/src/configurationPlugin.ts +2 -2
- package/src/consentApp.test.ts +12 -12
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/expressServer.ts +5 -11
- package/src/githubAuth.ts +3 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +40 -1
- package/src/middleware.ts +15 -0
- package/src/models/versionConfig.ts +1 -1
- package/src/openApiBuilder.test.ts +9 -24
- package/src/openApiCompat.ts +99 -45
- package/src/openApiValidator.test.ts +0 -41
- package/src/permissions.test.ts +75 -1
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +54 -14
- package/src/plugins.ts +47 -9
- package/src/populate.test.ts +16 -25
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -239
- package/src/realtime/realtimeApp.ts +80 -19
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +40 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +703 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +640 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +738 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/src/tests/models.ts +6 -8
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- package/src/realtime/realtimeAppSetup.test.ts +0 -161
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/src/api.ts
CHANGED
|
@@ -18,15 +18,14 @@ import {
|
|
|
18
18
|
import {authenticateMiddleware, type User} from "./auth";
|
|
19
19
|
import {
|
|
20
20
|
APIError,
|
|
21
|
-
type APIErrorOptions,
|
|
22
21
|
apiErrorMiddleware,
|
|
23
22
|
BadRequestError,
|
|
24
23
|
errorDetail,
|
|
25
24
|
ForbiddenError,
|
|
26
|
-
getDisableExternalErrorTracking,
|
|
27
25
|
isAPIError,
|
|
28
|
-
mongooseErrorToAPIError,
|
|
29
26
|
NotFoundError,
|
|
27
|
+
passthroughOrWrap,
|
|
28
|
+
passthroughOrWrapWrite,
|
|
30
29
|
} from "./errors";
|
|
31
30
|
import {logger} from "./logger";
|
|
32
31
|
import {
|
|
@@ -46,6 +45,15 @@ import {checkPermissions, permissionMiddleware, type RESTPermissions} from "./pe
|
|
|
46
45
|
import type {PopulatePath} from "./populate";
|
|
47
46
|
import {registerRealtime} from "./realtime/registry";
|
|
48
47
|
import type {RealtimeConfig} from "./realtime/types";
|
|
48
|
+
import {
|
|
49
|
+
type ExecutorConcurrencyCheck,
|
|
50
|
+
executeCreate,
|
|
51
|
+
executeDelete,
|
|
52
|
+
executeUpdate,
|
|
53
|
+
isExecutorConflictError,
|
|
54
|
+
} from "./sync/executors";
|
|
55
|
+
import {registerSync} from "./sync/registry";
|
|
56
|
+
import type {SyncConfig} from "./sync/types";
|
|
49
57
|
import {
|
|
50
58
|
defaultResponseHandler,
|
|
51
59
|
serialize,
|
|
@@ -54,10 +62,6 @@ import {
|
|
|
54
62
|
} from "./transformers";
|
|
55
63
|
import {isValidObjectId} from "./utils";
|
|
56
64
|
|
|
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
|
-
|
|
61
65
|
export type JSONPrimitive = string | number | boolean | null;
|
|
62
66
|
export interface JSONArray extends Array<JSONValue> {}
|
|
63
67
|
export interface JSONObject {
|
|
@@ -65,39 +69,6 @@ export interface JSONObject {
|
|
|
65
69
|
}
|
|
66
70
|
export type JSONValue = JSONPrimitive | JSONObject | JSONArray;
|
|
67
71
|
|
|
68
|
-
/**
|
|
69
|
-
* Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
|
|
70
|
-
* An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
|
|
71
|
-
* anything else is wrapped in the given framework error. `wrapper` may override any field,
|
|
72
|
-
* including `detail`, which defaults to the caught error's text.
|
|
73
|
-
*/
|
|
74
|
-
const passthroughOrWrap = (error: unknown, wrapper: APIErrorOptions): APIError => {
|
|
75
|
-
if (isAPIError(error)) {
|
|
76
|
-
return error;
|
|
77
|
-
}
|
|
78
|
-
return new APIError({
|
|
79
|
-
cause: error,
|
|
80
|
-
detail: errorDetail(error),
|
|
81
|
-
disableExternalErrorTracking: getDisableExternalErrorTracking(error),
|
|
82
|
-
...wrapper,
|
|
83
|
-
});
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
/**
|
|
87
|
-
* `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
|
|
88
|
-
* errors are converted first so their per-field messages survive as `meta.fields` instead of being
|
|
89
|
-
* flattened into the wrapper's `detail`.
|
|
90
|
-
*/
|
|
91
|
-
const passthroughOrWrapWrite = (error: unknown, wrapper: APIErrorOptions): APIError => {
|
|
92
|
-
if (!isAPIError(error) && error instanceof Error) {
|
|
93
|
-
const converted = mongooseErrorToAPIError(error);
|
|
94
|
-
if (converted) {
|
|
95
|
-
return converted;
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
return passthroughOrWrap(error, wrapper);
|
|
99
|
-
};
|
|
100
|
-
|
|
101
72
|
export const addPopulateToQuery = (
|
|
102
73
|
// noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
103
74
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
@@ -382,6 +353,15 @@ export interface ModelRouterOptions<T> {
|
|
|
382
353
|
* Requires the RealtimeApp plugin to be registered with TerrenoApp.
|
|
383
354
|
*/
|
|
384
355
|
realtime?: RealtimeConfig;
|
|
356
|
+
/**
|
|
357
|
+
* Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
|
|
358
|
+
* into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
|
|
359
|
+
*
|
|
360
|
+
* Requires the schema to use `isDeletedPlugin` (soft delete tombstones) and
|
|
361
|
+
* `syncPlugin` (per-stream `_syncSeq` stamping) — validated at registration.
|
|
362
|
+
* Only works with the three-argument form: modelRouter('/path', Model, options).
|
|
363
|
+
*/
|
|
364
|
+
sync?: SyncConfig;
|
|
385
365
|
}
|
|
386
366
|
|
|
387
367
|
/**
|
|
@@ -407,7 +387,7 @@ const parseDateRangeBound = (rawValue: unknown, queryKey: string): Date => {
|
|
|
407
387
|
* so admin changelist date-range filters map to valid Mongoose range queries.
|
|
408
388
|
*/
|
|
409
389
|
const mergeDateRangeQueryParams = <T>(
|
|
410
|
-
model:
|
|
390
|
+
model: Model<T>,
|
|
411
391
|
query: Record<string, unknown>
|
|
412
392
|
): Record<string, unknown> => {
|
|
413
393
|
const schema = model.schema;
|
|
@@ -530,7 +510,7 @@ const shouldValidate = <T>(
|
|
|
530
510
|
|
|
531
511
|
// Get body validation middleware if validation is enabled
|
|
532
512
|
const getBodyValidationMiddleware = <T>(
|
|
533
|
-
model:
|
|
513
|
+
model: Model<T>,
|
|
534
514
|
options: ModelRouterOptions<T>,
|
|
535
515
|
operation: "create" | "update"
|
|
536
516
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
@@ -560,7 +540,7 @@ const getBodyValidationMiddleware = <T>(
|
|
|
560
540
|
|
|
561
541
|
// Get query validation middleware if validation is enabled
|
|
562
542
|
const getQueryValidationMiddleware = <T>(
|
|
563
|
-
model:
|
|
543
|
+
model: Model<T>,
|
|
564
544
|
options: ModelRouterOptions<T>
|
|
565
545
|
): ((req: Request, res: Response, next: NextFunction) => void) => {
|
|
566
546
|
const querySchema = buildQuerySchemaFromFields(model, options.queryFields);
|
|
@@ -611,22 +591,22 @@ export interface ModelRouterRegistration {
|
|
|
611
591
|
*/
|
|
612
592
|
export function modelRouter<T>(
|
|
613
593
|
path: string,
|
|
614
|
-
model:
|
|
594
|
+
model: Model<T>,
|
|
615
595
|
options: ModelRouterOptions<T>
|
|
616
596
|
): ModelRouterRegistration;
|
|
617
|
-
export function modelRouter<T>(model:
|
|
597
|
+
export function modelRouter<T>(model: Model<T>, options: ModelRouterOptions<T>): express.Router;
|
|
618
598
|
export function modelRouter<T>(
|
|
619
|
-
pathOrModel: string |
|
|
620
|
-
modelOrOptions:
|
|
599
|
+
pathOrModel: string | Model<T>,
|
|
600
|
+
modelOrOptions: Model<T> | ModelRouterOptions<T>,
|
|
621
601
|
maybeOptions?: ModelRouterOptions<T>
|
|
622
602
|
): express.Router | ModelRouterRegistration {
|
|
623
|
-
let model:
|
|
603
|
+
let model: Model<T>;
|
|
624
604
|
let options: ModelRouterOptions<T>;
|
|
625
605
|
let path: string | undefined;
|
|
626
606
|
|
|
627
607
|
if (typeof pathOrModel === "string") {
|
|
628
608
|
path = pathOrModel;
|
|
629
|
-
model = modelOrOptions as
|
|
609
|
+
model = modelOrOptions as Model<T>;
|
|
630
610
|
options = maybeOptions as ModelRouterOptions<T>;
|
|
631
611
|
} else {
|
|
632
612
|
model = pathOrModel;
|
|
@@ -646,6 +626,10 @@ export function modelRouter<T>(
|
|
|
646
626
|
routePath: path,
|
|
647
627
|
});
|
|
648
628
|
}
|
|
629
|
+
// Register for local-first sync if configured (validates the schema contract)
|
|
630
|
+
if (options.sync) {
|
|
631
|
+
registerSync({config: options.sync, model, options, routePath: path});
|
|
632
|
+
}
|
|
649
633
|
return {
|
|
650
634
|
__type: "modelRouter",
|
|
651
635
|
_buildWithOpenApi: (openApi: OpenApiMiddleware) =>
|
|
@@ -661,14 +645,17 @@ export function modelRouter<T>(
|
|
|
661
645
|
"Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)"
|
|
662
646
|
);
|
|
663
647
|
}
|
|
648
|
+
if (options.sync) {
|
|
649
|
+
logger.warn(
|
|
650
|
+
`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
|
|
651
|
+
"Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)"
|
|
652
|
+
);
|
|
653
|
+
}
|
|
664
654
|
|
|
665
655
|
return router;
|
|
666
656
|
}
|
|
667
657
|
|
|
668
|
-
const _buildModelRouter = <T>(
|
|
669
|
-
model: ModelLike<T>,
|
|
670
|
-
options: ModelRouterOptions<T>
|
|
671
|
-
): express.Router => {
|
|
658
|
+
const _buildModelRouter = <T>(model: Model<T>, options: ModelRouterOptions<T>): express.Router => {
|
|
672
659
|
const router = express.Router();
|
|
673
660
|
|
|
674
661
|
assertNoActionCollisions(model, options);
|
|
@@ -695,88 +682,15 @@ const _buildModelRouter = <T>(
|
|
|
695
682
|
createValidation,
|
|
696
683
|
],
|
|
697
684
|
asyncHandler(async (req: Request, res: Response) => {
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
title: "Transform error",
|
|
706
|
-
});
|
|
707
|
-
}
|
|
708
|
-
if (options.preCreate) {
|
|
709
|
-
try {
|
|
710
|
-
body = await options.preCreate(body, req);
|
|
711
|
-
} catch (error: unknown) {
|
|
712
|
-
throw passthroughOrWrap(error, {
|
|
713
|
-
code: "pre-create-hook-error",
|
|
714
|
-
status: 400,
|
|
715
|
-
title: "preCreate hook error",
|
|
716
|
-
});
|
|
717
|
-
}
|
|
718
|
-
if (body === undefined) {
|
|
719
|
-
throw new ForbiddenError({
|
|
720
|
-
code: "create-not-allowed",
|
|
721
|
-
detail: "A body must be returned from preCreate",
|
|
722
|
-
title: "Create not allowed",
|
|
723
|
-
});
|
|
724
|
-
}
|
|
725
|
-
if (body === null) {
|
|
726
|
-
throw new ForbiddenError({
|
|
727
|
-
code: "create-not-allowed",
|
|
728
|
-
detail: "preCreate hook returned null",
|
|
729
|
-
title: "Create not allowed",
|
|
730
|
-
});
|
|
731
|
-
}
|
|
732
|
-
}
|
|
733
|
-
if (body === undefined) {
|
|
734
|
-
throw new BadRequestError({
|
|
735
|
-
code: "invalid-request-body",
|
|
736
|
-
detail: "Body is undefined",
|
|
737
|
-
title: "Invalid request body",
|
|
738
|
-
});
|
|
739
|
-
}
|
|
740
|
-
let data: Document<unknown, unknown, unknown> & T;
|
|
741
|
-
try {
|
|
742
|
-
data = (await model.create(body as T)) as Document<unknown, unknown, unknown> & T;
|
|
743
|
-
} catch (error: unknown) {
|
|
744
|
-
throw passthroughOrWrapWrite(error, {
|
|
745
|
-
code: "create-error",
|
|
746
|
-
status: 400,
|
|
747
|
-
title: "Create error",
|
|
748
|
-
});
|
|
749
|
-
}
|
|
750
|
-
|
|
751
|
-
if (options.populatePaths) {
|
|
752
|
-
try {
|
|
753
|
-
// noExplicitAny: mongoose Query type varies based on populatePaths
|
|
754
|
-
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
|
|
755
|
-
let populateQuery: any = model.findById(data._id);
|
|
756
|
-
populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
|
|
757
|
-
data = await populateQuery.exec();
|
|
758
|
-
} catch (error: unknown) {
|
|
759
|
-
throw passthroughOrWrap(error, {
|
|
760
|
-
code: "populate-error",
|
|
761
|
-
status: 400,
|
|
762
|
-
title: "Populate error",
|
|
763
|
-
});
|
|
764
|
-
}
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
if (options.postCreate) {
|
|
768
|
-
try {
|
|
769
|
-
await options.postCreate(data, req);
|
|
770
|
-
} catch (error: unknown) {
|
|
771
|
-
throw passthroughOrWrap(error, {
|
|
772
|
-
code: "post-create-hook-error",
|
|
773
|
-
status: 400,
|
|
774
|
-
title: "postCreate hook error",
|
|
775
|
-
});
|
|
776
|
-
}
|
|
777
|
-
}
|
|
685
|
+
const {doc} = await executeCreate<T>({
|
|
686
|
+
body: req.body,
|
|
687
|
+
model,
|
|
688
|
+
options,
|
|
689
|
+
req,
|
|
690
|
+
user: req.user,
|
|
691
|
+
});
|
|
778
692
|
try {
|
|
779
|
-
const serialized = await responseHandler(
|
|
693
|
+
const serialized = await responseHandler(doc, "create", req, options);
|
|
780
694
|
return res.status(201).json({data: serialized});
|
|
781
695
|
} catch (error: unknown) {
|
|
782
696
|
throw passthroughOrWrap(error, {
|
|
@@ -985,57 +899,12 @@ const _buildModelRouter = <T>(
|
|
|
985
899
|
updateValidation,
|
|
986
900
|
],
|
|
987
901
|
asyncHandler(async (req: Request, res: Response) => {
|
|
988
|
-
|
|
902
|
+
const existingDoc: mongoose.Document & T = (req as Request & {obj: mongoose.Document & T})
|
|
903
|
+
.obj;
|
|
989
904
|
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
try {
|
|
993
|
-
body = transform<T>(options, req.body, "update", req.user) as Partial<T>;
|
|
994
|
-
} catch (error: unknown) {
|
|
995
|
-
throw passthroughOrWrap(error, {
|
|
996
|
-
code: "transform-error",
|
|
997
|
-
detail: `PATCH failed on ${req.params.id} for user ${req.user?.id}: ${errorDetail(error)}`,
|
|
998
|
-
status: 403,
|
|
999
|
-
title: "PATCH failed",
|
|
1000
|
-
});
|
|
1001
|
-
}
|
|
1002
|
-
|
|
1003
|
-
// Remove _updatedAt from body before preUpdate processes it
|
|
905
|
+
// Read `_updatedAt` before the executor strips it from the body; the executor's
|
|
906
|
+
// conflict detection still runs after preUpdate, matching the previous inline order.
|
|
1004
907
|
const bodyUpdatedAt = req.body._updatedAt;
|
|
1005
|
-
delete req.body._updatedAt;
|
|
1006
|
-
if (body && typeof body === "object") {
|
|
1007
|
-
delete (body as Record<string, unknown>)._updatedAt;
|
|
1008
|
-
}
|
|
1009
|
-
|
|
1010
|
-
if (options.preUpdate) {
|
|
1011
|
-
try {
|
|
1012
|
-
body = await options.preUpdate(body, req);
|
|
1013
|
-
} catch (error: unknown) {
|
|
1014
|
-
throw passthroughOrWrap(error, {
|
|
1015
|
-
code: "pre-update-hook-error",
|
|
1016
|
-
detail: `preUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
|
|
1017
|
-
status: 400,
|
|
1018
|
-
title: "preUpdate hook error",
|
|
1019
|
-
});
|
|
1020
|
-
}
|
|
1021
|
-
if (body === undefined) {
|
|
1022
|
-
throw new ForbiddenError({
|
|
1023
|
-
code: "update-not-allowed",
|
|
1024
|
-
detail: "A body must be returned from preUpdate",
|
|
1025
|
-
title: "Update not allowed",
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
if (body === null) {
|
|
1029
|
-
throw new ForbiddenError({
|
|
1030
|
-
code: "update-not-allowed",
|
|
1031
|
-
detail: `preUpdate hook on ${req.params.id} returned null`,
|
|
1032
|
-
title: "Update not allowed",
|
|
1033
|
-
});
|
|
1034
|
-
}
|
|
1035
|
-
}
|
|
1036
|
-
|
|
1037
|
-
// Conflict detection runs after preUpdate so that unauthorized mutations
|
|
1038
|
-
// are rejected before we leak document data in a 409 response.
|
|
1039
908
|
const preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
|
|
1040
909
|
const httpUnmodifiedSince = req.headers["if-unmodified-since"];
|
|
1041
910
|
const timestampValue = Array.isArray(preciseUnmodifiedSince)
|
|
@@ -1044,6 +913,8 @@ const _buildModelRouter = <T>(
|
|
|
1044
913
|
const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
|
|
1045
914
|
? httpUnmodifiedSince[0]
|
|
1046
915
|
: httpUnmodifiedSince;
|
|
916
|
+
|
|
917
|
+
let concurrencyCheck: ExecutorConcurrencyCheck | undefined;
|
|
1047
918
|
if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
|
|
1048
919
|
const usingPreciseHeader = Boolean(timestampValue);
|
|
1049
920
|
const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
|
|
@@ -1052,82 +923,47 @@ const _buildModelRouter = <T>(
|
|
|
1052
923
|
: httpTimestampValue
|
|
1053
924
|
? DateTime.fromHTTP(httpTimestampValue)
|
|
1054
925
|
: DateTime.fromISO(bodyUpdatedAt);
|
|
926
|
+
concurrencyCheck = {
|
|
927
|
+
// An unparseable value round-trips as an invalid Date; the executor turns it into
|
|
928
|
+
// the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
|
|
929
|
+
ifUnmodifiedSince: clientTimestamp.toJSDate(),
|
|
930
|
+
invalidTimestampDetail: usingPreciseHeader
|
|
931
|
+
? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
|
|
932
|
+
: usingHttpHeader
|
|
933
|
+
? "If-Unmodified-Since header could not be parsed as an HTTP date"
|
|
934
|
+
: "_updatedAt body field could not be parsed as an ISO date",
|
|
935
|
+
type: "timestamp",
|
|
936
|
+
};
|
|
937
|
+
}
|
|
1055
938
|
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
if (serverTimestamp && !serverTimestamp.isValid) {
|
|
1078
|
-
throw new BadRequestError({
|
|
1079
|
-
code: "invalid-server-timestamp",
|
|
1080
|
-
detail: "Document timestamp could not be parsed as a date",
|
|
1081
|
-
title: "Invalid server timestamp",
|
|
1082
|
-
});
|
|
1083
|
-
}
|
|
1084
|
-
|
|
1085
|
-
if (serverTimestamp && clientTimestamp < serverTimestamp) {
|
|
1086
|
-
const serialized = await responseHandler(doc, "update", req, options);
|
|
939
|
+
let doc: Document<unknown, unknown, unknown> & T;
|
|
940
|
+
try {
|
|
941
|
+
({doc} = await executeUpdate<T>({
|
|
942
|
+
body: req.body,
|
|
943
|
+
concurrencyCheck,
|
|
944
|
+
existingDoc,
|
|
945
|
+
id: req.params.id as string,
|
|
946
|
+
model,
|
|
947
|
+
options,
|
|
948
|
+
req,
|
|
949
|
+
user: req.user,
|
|
950
|
+
}));
|
|
951
|
+
} catch (error: unknown) {
|
|
952
|
+
// Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
|
|
953
|
+
if (isExecutorConflictError(error)) {
|
|
954
|
+
const serialized = await responseHandler(
|
|
955
|
+
error.doc as Document<unknown, unknown, unknown> & T,
|
|
956
|
+
"update",
|
|
957
|
+
req,
|
|
958
|
+
options
|
|
959
|
+
);
|
|
1087
960
|
return res.status(409).json({
|
|
1088
961
|
data: serialized,
|
|
1089
962
|
error: "Conflict",
|
|
1090
963
|
message: "Document was modified since your last read",
|
|
1091
964
|
});
|
|
1092
965
|
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
// Make a copy for passing pre-saved values to hooks.
|
|
1096
|
-
const prevDoc = cloneDeep(doc);
|
|
1097
|
-
|
|
1098
|
-
// Using .save here runs the risk of a versioning error if you try to make two simultaneous
|
|
1099
|
-
// updates. We won't wind up with corrupted data, just an API error.
|
|
1100
|
-
try {
|
|
1101
|
-
doc.set(body);
|
|
1102
|
-
await doc.save();
|
|
1103
|
-
} catch (error: unknown) {
|
|
1104
|
-
throw passthroughOrWrapWrite(error, {
|
|
1105
|
-
code: "update-save-error",
|
|
1106
|
-
detail: `preUpdate hook save error on ${req.params.id}: ${errorDetail(error)}`,
|
|
1107
|
-
status: 400,
|
|
1108
|
-
title: "preUpdate hook save error",
|
|
1109
|
-
});
|
|
1110
|
-
}
|
|
1111
|
-
|
|
1112
|
-
if (options.populatePaths) {
|
|
1113
|
-
// noExplicitAny: mongoose Query type varies based on populatePaths
|
|
1114
|
-
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
|
|
1115
|
-
let populateQuery: any = model.findById(doc._id);
|
|
1116
|
-
populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
|
|
1117
|
-
doc = await populateQuery.exec();
|
|
1118
|
-
}
|
|
1119
|
-
|
|
1120
|
-
if (options.postUpdate) {
|
|
1121
|
-
try {
|
|
1122
|
-
await options.postUpdate(doc, body, req, prevDoc);
|
|
1123
|
-
} catch (error: unknown) {
|
|
1124
|
-
throw passthroughOrWrap(error, {
|
|
1125
|
-
code: "post-update-hook-error",
|
|
1126
|
-
detail: `postUpdate hook error on ${req.params.id}: ${errorDetail(error)}`,
|
|
1127
|
-
status: 400,
|
|
1128
|
-
title: "postUpdate hook error",
|
|
1129
|
-
});
|
|
1130
|
-
}
|
|
966
|
+
throw error;
|
|
1131
967
|
}
|
|
1132
968
|
|
|
1133
969
|
try {
|
|
@@ -1150,69 +986,18 @@ const _buildModelRouter = <T>(
|
|
|
1150
986
|
permissionMiddleware(model, options),
|
|
1151
987
|
],
|
|
1152
988
|
asyncHandler(async (req: Request, res: Response) => {
|
|
1153
|
-
const
|
|
989
|
+
const existingDoc: mongoose.Document & T & {deleted?: boolean} = (
|
|
1154
990
|
req as Request & {obj: mongoose.Document & T & {deleted?: boolean}}
|
|
1155
991
|
).obj;
|
|
1156
992
|
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
status: 403,
|
|
1166
|
-
title: "preDelete hook error",
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
1169
|
-
if (body === undefined) {
|
|
1170
|
-
throw new ForbiddenError({
|
|
1171
|
-
code: "delete-not-allowed",
|
|
1172
|
-
detail: "A body must be returned from preDelete",
|
|
1173
|
-
title: "Delete not allowed",
|
|
1174
|
-
});
|
|
1175
|
-
}
|
|
1176
|
-
if (body === null) {
|
|
1177
|
-
throw new ForbiddenError({
|
|
1178
|
-
code: "delete-not-allowed",
|
|
1179
|
-
detail: `preDelete hook for ${req.params.id} returned null`,
|
|
1180
|
-
title: "Delete not allowed",
|
|
1181
|
-
});
|
|
1182
|
-
}
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
// Support .deleted from isDeleted plugin
|
|
1186
|
-
if (
|
|
1187
|
-
Object.keys(model.schema.paths).includes("deleted") &&
|
|
1188
|
-
model.schema.paths.deleted.instance === "Boolean"
|
|
1189
|
-
) {
|
|
1190
|
-
doc.deleted = true;
|
|
1191
|
-
await doc.save();
|
|
1192
|
-
} else {
|
|
1193
|
-
// For models without the isDeleted plugin
|
|
1194
|
-
try {
|
|
1195
|
-
await doc.deleteOne();
|
|
1196
|
-
} catch (error: unknown) {
|
|
1197
|
-
throw passthroughOrWrap(error, {
|
|
1198
|
-
code: "delete-error",
|
|
1199
|
-
status: 400,
|
|
1200
|
-
title: "Delete error",
|
|
1201
|
-
});
|
|
1202
|
-
}
|
|
1203
|
-
}
|
|
1204
|
-
|
|
1205
|
-
if (options.postDelete) {
|
|
1206
|
-
try {
|
|
1207
|
-
await options.postDelete(req, doc);
|
|
1208
|
-
} catch (error: unknown) {
|
|
1209
|
-
throw passthroughOrWrap(error, {
|
|
1210
|
-
code: "post-delete-hook-error",
|
|
1211
|
-
status: 400,
|
|
1212
|
-
title: "postDelete hook error",
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
993
|
+
await executeDelete<T>({
|
|
994
|
+
existingDoc,
|
|
995
|
+
id: req.params.id as string,
|
|
996
|
+
model,
|
|
997
|
+
options,
|
|
998
|
+
req,
|
|
999
|
+
user: req.user,
|
|
1000
|
+
});
|
|
1216
1001
|
|
|
1217
1002
|
return res.status(204).json({});
|
|
1218
1003
|
})
|
|
@@ -1396,11 +1181,7 @@ const _buildModelRouter = <T>(
|
|
|
1396
1181
|
return arrayOperation(req, res, "DELETE");
|
|
1397
1182
|
};
|
|
1398
1183
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1399
|
-
if (
|
|
1400
|
-
(Object.values(model.schema.paths) as mongoose.SchemaType[]).find(
|
|
1401
|
-
(config) => config.instance === "Array"
|
|
1402
|
-
)
|
|
1403
|
-
) {
|
|
1184
|
+
if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
|
|
1404
1185
|
router.post(
|
|
1405
1186
|
"/:id/:field",
|
|
1406
1187
|
authenticateMiddleware(options.allowAnonymous),
|