@terreno/api 57.4.0 → 57.6.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/README.md +5 -5
- package/bunfig.toml +1 -1
- package/dist/actions.js +197 -368
- package/dist/adminModelRouter.js +88 -173
- package/dist/api.js +617 -852
- package/dist/audit/auditApp.js +48 -89
- package/dist/audit/auditEventModel.js +15 -16
- package/dist/audit/cloudTasksEnqueue.js +56 -149
- package/dist/audit/diff.js +70 -160
- package/dist/audit/processQueue.js +25 -70
- package/dist/audit/rbacSink.js +25 -66
- package/dist/audit/record.js +129 -251
- package/dist/auth.js +432 -681
- package/dist/authRecovery.js +155 -269
- package/dist/authTokens.js +43 -118
- package/dist/betterAuthApp.js +25 -26
- package/dist/betterAuthSetup.js +258 -413
- package/dist/browserLogsRoute.d.ts +6 -0
- package/dist/browserLogsRoute.js +97 -0
- package/dist/collectionRegistry.js +32 -47
- package/dist/config.js +53 -122
- package/dist/configurationApp.js +180 -361
- package/dist/configurationPlugin.js +130 -302
- package/dist/consentApp.js +276 -421
- package/dist/docLoader.js +78 -126
- package/dist/envConfigurationPlugin.js +25 -147
- package/dist/errors.js +151 -247
- package/dist/example.js +28 -34
- package/dist/expressServer.d.ts +10 -0
- package/dist/expressServer.js +109 -255
- package/dist/frameworkModelNames.d.ts +24 -0
- package/dist/frameworkModelNames.js +31 -0
- package/dist/githubAuth.js +152 -216
- package/dist/httpClient.js +176 -264
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -2
- package/dist/logger.js +145 -278
- package/dist/mcp/auth.js +76 -128
- package/dist/mcp/createMCPRequest.js +4 -5
- package/dist/mcp/handlers.js +268 -480
- package/dist/mcp/query.js +56 -150
- package/dist/mcp/registry.js +17 -30
- package/dist/mcp/schemaGenerator.js +95 -181
- package/dist/mcp/server.js +28 -100
- package/dist/mcp/serviceTokens.js +102 -191
- package/dist/mcp/toolGenerator.js +78 -191
- package/dist/middleware.js +15 -27
- package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
- package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
- package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
- package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
- package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
- package/dist/migrations/generate.js +107 -229
- package/dist/migrations/load.js +75 -201
- package/dist/migrations/lock.js +54 -126
- package/dist/migrations/runner.js +192 -446
- package/dist/migrations/schemaCatalog.js +122 -263
- package/dist/models/consentForm.js +6 -6
- package/dist/models/consentResponse.js +5 -5
- package/dist/models/mcpServiceToken.js +66 -156
- package/dist/models/notification.js +6 -6
- package/dist/models/notificationPreference.js +6 -6
- package/dist/models/versionConfig.js +5 -5
- package/dist/notifications/notificationService.js +133 -273
- package/dist/notifications/notificationsApp.js +85 -179
- package/dist/notifications/notificationsBeforeSend.js +19 -64
- package/dist/notifiers/googleChatNotifier.js +36 -117
- package/dist/notifiers/slackNotifier.d.ts +31 -2
- package/dist/notifiers/slackNotifier.js +170 -119
- package/dist/notifiers/zoomNotifier.js +60 -111
- package/dist/openApi.js +107 -122
- package/dist/openApiBuilder.js +117 -159
- package/dist/openApiCompat.js +81 -148
- package/dist/openApiEtag.js +7 -7
- package/dist/openApiValidator.js +177 -286
- package/dist/orgs/orgContext.js +87 -157
- package/dist/orgs/orgPermissions.js +29 -68
- package/dist/orgs/orgPlugin.js +9 -27
- package/dist/orgs/organizationModel.js +65 -166
- package/dist/orgs/organizationSettings.js +29 -36
- package/dist/orgs/orgsApp.js +346 -608
- package/dist/permissions.js +88 -181
- package/dist/plugins.js +125 -218
- package/dist/populate.js +130 -240
- package/dist/rateLimit/applyTrustProxy.js +1 -1
- package/dist/rateLimit/createStore.js +7 -8
- package/dist/rateLimit/memoryStore.js +22 -100
- package/dist/rateLimit/middleware.js +48 -99
- package/dist/rateLimit/mongoStore.js +54 -112
- package/dist/rateLimit/policies.js +41 -75
- package/dist/rateLimit/redisStore.js +39 -133
- package/dist/rbac/access.js +119 -267
- package/dist/rbac/assertAllowed.js +95 -171
- package/dist/rbac/auditModel.js +14 -58
- package/dist/rbac/backfillAdmins.js +24 -130
- package/dist/rbac/fieldViews.js +46 -141
- package/dist/rbac/membershipOrgAdminSource.js +28 -99
- package/dist/rbac/middleware.js +30 -96
- package/dist/rbac/modelRouterAccess.js +130 -307
- package/dist/rbac/permissionUtils.js +40 -179
- package/dist/rbac/realtimeAccess.js +81 -147
- package/dist/rbac/resolve.d.ts +1 -1
- package/dist/rbac/resolve.js +148 -342
- package/dist/rbac/roleManager.js +318 -700
- package/dist/rbac/roleModel.js +44 -171
- package/dist/rbac/routes.js +93 -196
- package/dist/rbac/scopes.js +39 -133
- package/dist/rbac/statements.js +23 -91
- package/dist/rbac/userPlugin.js +3 -29
- package/dist/realtime/changeStreamWatcher.js +489 -800
- package/dist/realtime/deprecation.js +8 -10
- package/dist/realtime/queryMatcher.js +110 -191
- package/dist/realtime/queryStore.js +35 -118
- package/dist/realtime/realtimeApp.js +247 -401
- package/dist/realtime/registry.js +19 -30
- package/dist/realtime/sessionRevalidation.js +132 -358
- package/dist/realtime/socketAuth.js +89 -208
- package/dist/realtime/socketUser.js +10 -56
- package/dist/requestContext.js +93 -139
- package/dist/schemaMetadata.js +179 -274
- package/dist/scriptRunner.js +96 -266
- package/dist/scrubAdminFields.js +36 -108
- package/dist/secretProviders.js +130 -299
- package/dist/seedRunner.js +221 -514
- package/dist/sync/adminBroadcastScope.js +58 -170
- package/dist/sync/adminWindowAccess.js +15 -86
- package/dist/sync/adminWindowMutation.js +110 -181
- package/dist/sync/executors.js +425 -629
- package/dist/sync/loadHarness.js +392 -689
- package/dist/sync/models.js +181 -341
- package/dist/sync/mutationHandler.js +533 -801
- package/dist/sync/registrationSideEffects.js +41 -95
- package/dist/sync/registry.js +29 -49
- package/dist/sync/routes.js +484 -817
- package/dist/sync/scripts/compactTombstones.js +83 -228
- package/dist/sync/serialize.js +18 -58
- package/dist/sync/socketHandlers.js +253 -478
- package/dist/sync/streams.js +49 -117
- package/dist/sync/syncApp.js +12 -15
- package/dist/sync/syncBatch.js +63 -168
- package/dist/sync/syncSeqPlugin.js +430 -702
- package/dist/syncConsents.js +113 -253
- package/dist/terrenoApp.js +166 -276
- package/dist/tests/createTestData.js +146 -256
- package/dist/tests/models.js +14 -54
- package/dist/tests/mongoTestSetup.js +42 -103
- package/dist/tests/testHelper.js +31 -93
- package/dist/tests.js +12 -51
- package/dist/transformers.js +61 -164
- package/dist/utils.js +31 -93
- package/dist/vendor/wesleytodd-openapi/index.js +37 -51
- package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
- package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
- package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
- package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
- package/dist/versionCheckPlugin.js +52 -100
- package/dist/webhooks/headerValue.js +2 -2
- package/dist/webhooks/idempotency/memoryStore.js +16 -59
- package/dist/webhooks/idempotency/mongoStore.js +55 -130
- package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
- package/dist/webhooks/rawBody.js +1 -1
- package/dist/webhooks/timingSafeEqual.js +4 -5
- package/dist/webhooks/verifiers/hmac.js +17 -18
- package/dist/webhooks/verifiers/sendgrid.js +20 -22
- package/dist/webhooks/verifiers/stripe.js +31 -65
- package/dist/webhooks/verifiers/twilio.js +23 -73
- package/dist/webhooks/webhooksApp.js +78 -177
- package/dist/zodOpenApi.js +2 -2
- package/package.json +6 -6
- package/src/__tests__/browserLogsRoute.test.ts +165 -0
- package/src/api.arrayOperations.test.ts +44 -0
- package/src/api.ts +64 -39
- package/src/audit/auditApp.test.ts +5 -5
- package/src/audit/auditEventModel.ts +7 -3
- package/src/audit/auditRouter.test.ts +5 -5
- package/src/audit/rbacSink.test.ts +2 -2
- package/src/audit/record.test.ts +2 -2
- package/src/audit/record.ts +3 -2
- package/src/auth.ts +1 -1
- package/src/authRecovery.test.ts +43 -0
- package/src/authRecovery.ts +16 -10
- package/src/authTokens.ts +6 -2
- package/src/authVerification.test.ts +22 -0
- package/src/browserLogsRoute.ts +110 -0
- package/src/configurationPlugin.test.ts +1 -11
- package/src/expressServer.ts +10 -0
- package/src/frameworkModelNames.test.ts +62 -0
- package/src/frameworkModelNames.ts +33 -0
- package/src/index.ts +7 -0
- package/src/isolated/migrateCliConnect.isolated.ts +51 -0
- package/src/mcp/auth.test.ts +34 -1
- package/src/migrations/cli.test.ts +0 -23
- package/src/models/mcpServiceToken.ts +4 -3
- package/src/models/notification.ts +3 -2
- package/src/models/notificationPreference.ts +1 -1
- package/src/notifications/notificationsApp.test.ts +24 -1
- package/src/notifiers/slackNotifier.test.ts +186 -1
- package/src/notifiers/slackNotifier.ts +167 -8
- package/src/orgs/orgPlugin.ts +1 -1
- package/src/orgs/organizationModel.ts +11 -6
- package/src/plugins.test.ts +5 -0
- package/src/plugins.ts +3 -0
- package/src/realtime/realtimeApp.ts +1 -1
- package/src/sync/integration.test.ts +2 -2
- package/src/terrenoApp.ts +3 -0
- package/src/types.d.ts +1 -0
- package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
- package/tsconfig.json +13 -54
- package/tsconfig.typedoc.json +2 -0
package/dist/api.js
CHANGED
|
@@ -1,15 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __assign = (this && this.__assign) || function () {
|
|
3
|
-
__assign = Object.assign || function(t) {
|
|
4
|
-
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
5
|
-
s = arguments[i];
|
|
6
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
7
|
-
t[p] = s[p];
|
|
8
|
-
}
|
|
9
|
-
return t;
|
|
10
|
-
};
|
|
11
|
-
return __assign.apply(this, arguments);
|
|
12
|
-
};
|
|
13
2
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
14
3
|
if (k2 === undefined) k2 = k;
|
|
15
4
|
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
@@ -43,78 +32,6 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
43
32
|
return result;
|
|
44
33
|
};
|
|
45
34
|
})();
|
|
46
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
47
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
48
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
49
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
50
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
51
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
52
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
53
|
-
});
|
|
54
|
-
};
|
|
55
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
56
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
57
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
58
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
59
|
-
function step(op) {
|
|
60
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
61
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
62
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
63
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
64
|
-
switch (op[0]) {
|
|
65
|
-
case 0: case 1: t = op; break;
|
|
66
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
67
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
68
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
69
|
-
default:
|
|
70
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
71
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
72
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
73
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
74
|
-
if (t[2]) _.ops.pop();
|
|
75
|
-
_.trys.pop(); continue;
|
|
76
|
-
}
|
|
77
|
-
op = body.call(thisArg, _);
|
|
78
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
79
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
80
|
-
}
|
|
81
|
-
};
|
|
82
|
-
var __values = (this && this.__values) || function(o) {
|
|
83
|
-
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
|
|
84
|
-
if (m) return m.call(o);
|
|
85
|
-
if (o && typeof o.length === "number") return {
|
|
86
|
-
next: function () {
|
|
87
|
-
if (o && i >= o.length) o = void 0;
|
|
88
|
-
return { value: o && o[i++], done: !o };
|
|
89
|
-
}
|
|
90
|
-
};
|
|
91
|
-
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
|
|
92
|
-
};
|
|
93
|
-
var __read = (this && this.__read) || function (o, n) {
|
|
94
|
-
var m = typeof Symbol === "function" && o[Symbol.iterator];
|
|
95
|
-
if (!m) return o;
|
|
96
|
-
var i = m.call(o), r, ar = [], e;
|
|
97
|
-
try {
|
|
98
|
-
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
|
|
99
|
-
}
|
|
100
|
-
catch (error) { e = { error: error }; }
|
|
101
|
-
finally {
|
|
102
|
-
try {
|
|
103
|
-
if (r && !r.done && (m = i["return"])) m.call(i);
|
|
104
|
-
}
|
|
105
|
-
finally { if (e) throw e.error; }
|
|
106
|
-
}
|
|
107
|
-
return ar;
|
|
108
|
-
};
|
|
109
|
-
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
|
|
110
|
-
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
|
|
111
|
-
if (ar || !(i in from)) {
|
|
112
|
-
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
|
|
113
|
-
ar[i] = from[i];
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
return to.concat(ar || Array.prototype.slice.call(from));
|
|
117
|
-
};
|
|
118
35
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
119
36
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
120
37
|
};
|
|
@@ -126,48 +43,37 @@ exports.modelRouter = modelRouter;
|
|
|
126
43
|
*
|
|
127
44
|
* @packageDocumentation
|
|
128
45
|
*/
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
46
|
+
const Sentry = __importStar(require("@sentry/bun"));
|
|
47
|
+
const express_1 = __importDefault(require("express"));
|
|
48
|
+
const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
|
|
49
|
+
const luxon_1 = require("luxon");
|
|
50
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
51
|
+
const actions_1 = require("./actions");
|
|
52
|
+
const adminModelRouter_1 = require("./adminModelRouter");
|
|
53
|
+
const record_1 = require("./audit/record");
|
|
54
|
+
const auth_1 = require("./auth");
|
|
55
|
+
const collectionRegistry_1 = require("./collectionRegistry");
|
|
56
|
+
const errors_1 = require("./errors");
|
|
57
|
+
const logger_1 = require("./logger");
|
|
58
|
+
const registry_1 = require("./mcp/registry");
|
|
59
|
+
const openApi_1 = require("./openApi");
|
|
60
|
+
const openApiValidator_1 = require("./openApiValidator");
|
|
61
|
+
const permissions_1 = require("./permissions");
|
|
62
|
+
const modelRouterAccess_1 = require("./rbac/modelRouterAccess");
|
|
63
|
+
const deprecation_1 = require("./realtime/deprecation");
|
|
64
|
+
const executors_1 = require("./sync/executors");
|
|
65
|
+
const transformers_1 = require("./transformers");
|
|
66
|
+
const utils_1 = require("./utils");
|
|
67
|
+
const addPopulateToQuery = (
|
|
151
68
|
// noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
152
69
|
// biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
|
|
153
|
-
builtQuery, populatePaths) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
var path = populatePath.path;
|
|
161
|
-
var select = populatePath.fields;
|
|
162
|
-
query = builtQuery.populate({ path: path, select: select });
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
166
|
-
finally {
|
|
167
|
-
try {
|
|
168
|
-
if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);
|
|
169
|
-
}
|
|
170
|
-
finally { if (e_1) throw e_1.error; }
|
|
70
|
+
builtQuery, populatePaths) => {
|
|
71
|
+
const paths = populatePaths ?? [];
|
|
72
|
+
let query = builtQuery;
|
|
73
|
+
for (const populatePath of paths) {
|
|
74
|
+
const path = populatePath.path;
|
|
75
|
+
const select = populatePath.fields;
|
|
76
|
+
query = builtQuery.populate({ path, select });
|
|
171
77
|
}
|
|
172
78
|
return query;
|
|
173
79
|
};
|
|
@@ -177,20 +83,20 @@ exports.addPopulateToQuery = addPopulateToQuery;
|
|
|
177
83
|
// Support more complex query fields
|
|
178
84
|
// Rate limiting
|
|
179
85
|
// These are the query params that are reserved for pagination.
|
|
180
|
-
|
|
86
|
+
const PAGINATION_QUERY_PARAMS = ["limit", "page", "sort"];
|
|
181
87
|
// Add support for more complex queries.
|
|
182
|
-
|
|
88
|
+
const COMPLEX_QUERY_PARAMS = ["$and", "$or"];
|
|
183
89
|
/**
|
|
184
90
|
* Parses a date-range query bound from an ISO-8601 string using Luxon, throwing a 400
|
|
185
91
|
* APIError when the value cannot be parsed. Centralizes date-string parsing so the repo's
|
|
186
92
|
* Luxon convention is honored for admin changelist date-range filters.
|
|
187
93
|
*/
|
|
188
|
-
|
|
189
|
-
|
|
94
|
+
const parseDateRangeBound = (rawValue, queryKey) => {
|
|
95
|
+
const parsed = luxon_1.DateTime.fromISO(String(rawValue), { zone: "utc" });
|
|
190
96
|
if (!parsed.isValid) {
|
|
191
97
|
throw new errors_1.BadRequestError({
|
|
192
98
|
code: "invalid-date-query-parameter",
|
|
193
|
-
detail:
|
|
99
|
+
detail: `Invalid date for query parameter ${queryKey}`,
|
|
194
100
|
source: { parameter: queryKey },
|
|
195
101
|
title: "Invalid date query parameter",
|
|
196
102
|
});
|
|
@@ -201,114 +107,71 @@ var parseDateRangeBound = function (rawValue, queryKey) {
|
|
|
201
107
|
* Collapses `field_gte` / `field_lte` query pairs into `{ field: { $gte, $lte } }` for Date paths,
|
|
202
108
|
* so admin changelist date-range filters map to valid Mongoose range queries.
|
|
203
109
|
*/
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
var match = /^(.+)_(gte|lte)$/.exec(key);
|
|
213
|
-
if (!match) {
|
|
214
|
-
continue;
|
|
215
|
-
}
|
|
216
|
-
var baseField = match[1];
|
|
217
|
-
var path = schema.path(baseField);
|
|
218
|
-
if ((path === null || path === void 0 ? void 0 : path.instance) !== "Date") {
|
|
219
|
-
continue;
|
|
220
|
-
}
|
|
221
|
-
dateRangeBases.add(baseField);
|
|
110
|
+
const mergeDateRangeQueryParams = (model, query) => {
|
|
111
|
+
const schema = model.schema;
|
|
112
|
+
const result = { ...query };
|
|
113
|
+
const dateRangeBases = new Set();
|
|
114
|
+
for (const key of Object.keys(result)) {
|
|
115
|
+
const match = /^(.+)_(gte|lte)$/.exec(key);
|
|
116
|
+
if (!match) {
|
|
117
|
+
continue;
|
|
222
118
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
|
|
119
|
+
const baseField = match[1];
|
|
120
|
+
const path = schema.path(baseField);
|
|
121
|
+
if (path?.instance !== "Date") {
|
|
122
|
+
continue;
|
|
228
123
|
}
|
|
229
|
-
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
|
|
240
|
-
bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
|
|
241
|
-
}
|
|
242
|
-
if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
|
|
243
|
-
bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
|
|
244
|
-
}
|
|
245
|
-
if (Object.keys(bounds).length === 0) {
|
|
246
|
-
continue;
|
|
247
|
-
}
|
|
248
|
-
delete result[gteKey];
|
|
249
|
-
delete result[lteKey];
|
|
250
|
-
var direct = result[baseField];
|
|
251
|
-
if (direct !== undefined && direct !== null && typeof direct !== "object") {
|
|
252
|
-
delete result[baseField];
|
|
253
|
-
}
|
|
254
|
-
if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
|
|
255
|
-
result[baseField] = __assign(__assign({}, direct), bounds);
|
|
256
|
-
}
|
|
257
|
-
else {
|
|
258
|
-
result[baseField] = bounds;
|
|
259
|
-
}
|
|
124
|
+
dateRangeBases.add(baseField);
|
|
125
|
+
}
|
|
126
|
+
for (const baseField of dateRangeBases) {
|
|
127
|
+
const gteKey = `${baseField}_gte`;
|
|
128
|
+
const lteKey = `${baseField}_lte`;
|
|
129
|
+
const gteRaw = result[gteKey];
|
|
130
|
+
const lteRaw = result[lteKey];
|
|
131
|
+
const bounds = {};
|
|
132
|
+
if (gteRaw !== undefined && gteRaw !== null && String(gteRaw).trim() !== "") {
|
|
133
|
+
bounds.$gte = parseDateRangeBound(gteRaw, gteKey);
|
|
260
134
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
135
|
+
if (lteRaw !== undefined && lteRaw !== null && String(lteRaw).trim() !== "") {
|
|
136
|
+
bounds.$lte = parseDateRangeBound(lteRaw, lteKey);
|
|
137
|
+
}
|
|
138
|
+
if (Object.keys(bounds).length === 0) {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
delete result[gteKey];
|
|
142
|
+
delete result[lteKey];
|
|
143
|
+
const direct = result[baseField];
|
|
144
|
+
if (direct !== undefined && direct !== null && typeof direct !== "object") {
|
|
145
|
+
delete result[baseField];
|
|
146
|
+
}
|
|
147
|
+
if (typeof direct === "object" && direct !== null && !Array.isArray(direct)) {
|
|
148
|
+
result[baseField] = { ...direct, ...bounds };
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
result[baseField] = bounds;
|
|
266
152
|
}
|
|
267
|
-
finally { if (e_3) throw e_3.error; }
|
|
268
153
|
}
|
|
269
154
|
return result;
|
|
270
155
|
};
|
|
271
156
|
// Ensures query params are allowed. Also checks nested query params when using $and/$or.
|
|
272
|
-
|
|
273
|
-
var e_4, _a, e_5, _b;
|
|
274
|
-
if (queryFields === void 0) { queryFields = []; }
|
|
157
|
+
const checkQueryParamAllowed = (queryParam, queryParamValue, queryFields = []) => {
|
|
275
158
|
// Cast for iteration through complex query values
|
|
276
|
-
|
|
159
|
+
const complexValue = queryParamValue;
|
|
277
160
|
// Check the values of each of the complex query params. We don't support recursive queries here,
|
|
278
161
|
// just one level of and/or
|
|
279
162
|
if (COMPLEX_QUERY_PARAMS.includes(queryParam)) {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
for (
|
|
283
|
-
|
|
284
|
-
try {
|
|
285
|
-
for (var _c = (e_5 = void 0, __values(Object.keys(subQuery))), _d = _c.next(); !_d.done; _d = _c.next()) {
|
|
286
|
-
var subKey = _d.value;
|
|
287
|
-
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
catch (e_5_1) { e_5 = { error: e_5_1 }; }
|
|
291
|
-
finally {
|
|
292
|
-
try {
|
|
293
|
-
if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
|
|
294
|
-
}
|
|
295
|
-
finally { if (e_5) throw e_5.error; }
|
|
296
|
-
}
|
|
163
|
+
// Complex query of the form `$and: [{key1: value1}, {key2: value2}]`
|
|
164
|
+
for (const subQuery of complexValue) {
|
|
165
|
+
for (const subKey of Object.keys(subQuery)) {
|
|
166
|
+
checkQueryParamAllowed(subKey, subQuery[subKey], queryFields);
|
|
297
167
|
}
|
|
298
168
|
}
|
|
299
|
-
catch (e_4_1) { e_4 = { error: e_4_1 }; }
|
|
300
|
-
finally {
|
|
301
|
-
try {
|
|
302
|
-
if (complexValue_1_1 && !complexValue_1_1.done && (_a = complexValue_1.return)) _a.call(complexValue_1);
|
|
303
|
-
}
|
|
304
|
-
finally { if (e_4) throw e_4.error; }
|
|
305
|
-
}
|
|
306
169
|
return;
|
|
307
170
|
}
|
|
308
171
|
if (!queryFields.includes(queryParam)) {
|
|
309
172
|
throw new errors_1.BadRequestError({
|
|
310
173
|
code: "query-param-not-allowed",
|
|
311
|
-
detail:
|
|
174
|
+
detail: `${queryParam} is not allowed as a query param.`,
|
|
312
175
|
source: { parameter: queryParam },
|
|
313
176
|
title: "Query parameter not allowed",
|
|
314
177
|
});
|
|
@@ -335,27 +198,26 @@ var checkQueryParamAllowed = function (queryParam, queryParamValue, queryFields)
|
|
|
335
198
|
// Helper to determine if validation should be enabled for a specific operation.
|
|
336
199
|
// When options.validation is not set, returns true — the middleware's own
|
|
337
200
|
// isConfigured check will decide whether to actually validate.
|
|
338
|
-
|
|
339
|
-
var _a, _b, _c;
|
|
201
|
+
const shouldValidate = (options, operation) => {
|
|
340
202
|
// Check route-specific validation option first
|
|
341
203
|
if (options.validation !== undefined) {
|
|
342
204
|
if (typeof options.validation === "boolean") {
|
|
343
205
|
return options.validation;
|
|
344
206
|
}
|
|
345
207
|
if (operation === "create") {
|
|
346
|
-
return
|
|
208
|
+
return options.validation.validateCreate ?? true;
|
|
347
209
|
}
|
|
348
210
|
if (operation === "update") {
|
|
349
|
-
return
|
|
211
|
+
return options.validation.validateUpdate ?? true;
|
|
350
212
|
}
|
|
351
|
-
return
|
|
213
|
+
return options.validation.validateQuery ?? true;
|
|
352
214
|
}
|
|
353
215
|
// Default: let middleware's isConfigured check decide
|
|
354
216
|
return true;
|
|
355
217
|
};
|
|
356
218
|
// Get body validation middleware if validation is enabled
|
|
357
|
-
|
|
358
|
-
|
|
219
|
+
const getBodyValidationMiddleware = (model, options, operation) => {
|
|
220
|
+
const validationOptions = {};
|
|
359
221
|
if (!shouldValidate(options, operation)) {
|
|
360
222
|
validationOptions.enabled = false;
|
|
361
223
|
}
|
|
@@ -367,10 +229,10 @@ var getBodyValidationMiddleware = function (model, options, operation) {
|
|
|
367
229
|
validationOptions.onAdditionalPropertiesRemoved =
|
|
368
230
|
options.validation.onAdditionalPropertiesRemoved;
|
|
369
231
|
}
|
|
370
|
-
|
|
232
|
+
const excludeFields = operation === "create"
|
|
371
233
|
? options.validation.excludeFromCreate
|
|
372
234
|
: options.validation.excludeFromUpdate;
|
|
373
|
-
if (excludeFields
|
|
235
|
+
if (excludeFields?.length) {
|
|
374
236
|
validationOptions.excludeFields = excludeFields;
|
|
375
237
|
}
|
|
376
238
|
}
|
|
@@ -380,9 +242,9 @@ var getBodyValidationMiddleware = function (model, options, operation) {
|
|
|
380
242
|
return (0, openApiValidator_1.validateModelRequestBody)(model, validationOptions);
|
|
381
243
|
};
|
|
382
244
|
// Get query validation middleware if validation is enabled
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
245
|
+
const getQueryValidationMiddleware = (model, options) => {
|
|
246
|
+
const querySchema = (0, openApiValidator_1.buildQuerySchemaFromFields)(model, options.queryFields);
|
|
247
|
+
const validationOptions = {};
|
|
386
248
|
if (!shouldValidate(options, "query")) {
|
|
387
249
|
validationOptions.enabled = false;
|
|
388
250
|
}
|
|
@@ -392,9 +254,9 @@ var getQueryValidationMiddleware = function (model, options) {
|
|
|
392
254
|
return (0, openApiValidator_1.validateQueryParams)(querySchema, validationOptions);
|
|
393
255
|
};
|
|
394
256
|
function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
257
|
+
let model;
|
|
258
|
+
let options;
|
|
259
|
+
let path;
|
|
398
260
|
if (typeof pathOrModel === "string") {
|
|
399
261
|
path = pathOrModel;
|
|
400
262
|
model = modelOrOptions;
|
|
@@ -409,53 +271,62 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
|
|
|
409
271
|
if (options.mcp && path === undefined) {
|
|
410
272
|
(0, registry_1.registerMCPModel)(model, options.mcp, options);
|
|
411
273
|
}
|
|
412
|
-
|
|
274
|
+
const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
|
|
413
275
|
if (path !== undefined) {
|
|
414
276
|
if (options.realtime) {
|
|
415
277
|
(0, deprecation_1.warnRealtimeDeprecated)(model.modelName, path);
|
|
416
278
|
}
|
|
417
|
-
(0, collectionRegistry_1.registerCollection)({ model
|
|
279
|
+
(0, collectionRegistry_1.registerCollection)({ model, options, routePath: path });
|
|
418
280
|
}
|
|
419
|
-
|
|
281
|
+
const router = shouldDeferBuild ? express_1.default.Router() : _buildModelRouter(model, options, path);
|
|
420
282
|
if (path !== undefined) {
|
|
421
283
|
return {
|
|
422
284
|
__type: "modelRouter",
|
|
423
|
-
_buildWithContext:
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
285
|
+
_buildWithContext: (context) => {
|
|
286
|
+
const enrichedOptions = (0, adminModelRouter_1.enrichModelRouterOptions)(model, { ...options, openApi: context.openApi }, context);
|
|
287
|
+
const runtimeOptions = {
|
|
288
|
+
...enrichedOptions,
|
|
289
|
+
accessControl: enrichedOptions.accessControl ?? context.accessControl,
|
|
290
|
+
};
|
|
427
291
|
(0, collectionRegistry_1.replaceCollectionOptions)(path, runtimeOptions);
|
|
428
292
|
return _buildModelRouter(model, runtimeOptions, path);
|
|
429
293
|
},
|
|
430
|
-
model
|
|
431
|
-
options
|
|
432
|
-
path
|
|
433
|
-
router
|
|
294
|
+
model,
|
|
295
|
+
options,
|
|
296
|
+
path,
|
|
297
|
+
router,
|
|
434
298
|
};
|
|
435
299
|
}
|
|
436
300
|
if (options.realtime) {
|
|
437
301
|
(0, deprecation_1.warnRealtimeDeprecated)(model.modelName);
|
|
438
|
-
logger_1.logger.warn(
|
|
302
|
+
logger_1.logger.warn(`modelRouter for ${model.modelName} has realtime config but was called without a path. ` +
|
|
439
303
|
"Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
|
|
440
304
|
}
|
|
441
305
|
if (options.sync) {
|
|
442
|
-
logger_1.logger.warn(
|
|
306
|
+
logger_1.logger.warn(`modelRouter for ${model.modelName} has sync config but was called without a path. ` +
|
|
443
307
|
"Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)");
|
|
444
308
|
}
|
|
445
309
|
return router;
|
|
446
310
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
var resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
|
|
311
|
+
const _buildModelRouter = (model, options, routePath) => {
|
|
312
|
+
const router = express_1.default.Router();
|
|
313
|
+
const resolvedAccess = (0, modelRouterAccess_1.resolveModelRouterAccess)({
|
|
451
314
|
access: options.access,
|
|
452
315
|
accessControl: options.accessControl,
|
|
453
316
|
permissions: options.permissions,
|
|
454
317
|
queryFilter: options.queryFilter,
|
|
455
318
|
responseHandler: options.responseHandler,
|
|
456
|
-
scope:
|
|
319
|
+
scope: options.access?.scope,
|
|
457
320
|
});
|
|
458
|
-
options =
|
|
321
|
+
options = {
|
|
322
|
+
...options,
|
|
323
|
+
permissions: resolvedAccess.permissions,
|
|
324
|
+
queryFilter: (resolvedAccess.queryFilter ??
|
|
325
|
+
options.queryFilter),
|
|
326
|
+
responseHandler: (resolvedAccess.responseHandler ??
|
|
327
|
+
options.responseHandler ??
|
|
328
|
+
transformers_1.defaultResponseHandler),
|
|
329
|
+
};
|
|
459
330
|
if (routePath) {
|
|
460
331
|
(0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
|
|
461
332
|
}
|
|
@@ -468,636 +339,531 @@ var _buildModelRouter = function (model, options, routePath) {
|
|
|
468
339
|
if (options.endpoints) {
|
|
469
340
|
options.endpoints(router, options);
|
|
470
341
|
}
|
|
471
|
-
|
|
342
|
+
const responseHandler = options.responseHandler ?? transformers_1.defaultResponseHandler;
|
|
472
343
|
// Always install validation middleware — they are no-ops until configureOpenApiValidator() is called
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
344
|
+
const createValidation = getBodyValidationMiddleware(model, options, "create");
|
|
345
|
+
const updateValidation = getBodyValidationMiddleware(model, options, "update");
|
|
346
|
+
const queryValidation = getQueryValidationMiddleware(model, options);
|
|
476
347
|
router.post("/", [
|
|
477
348
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
478
349
|
(0, openApi_1.createOpenApiMiddleware)(model, options),
|
|
479
350
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
480
351
|
createValidation,
|
|
481
|
-
], (0, exports.asyncHandler)(
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
modelName: model.modelName,
|
|
498
|
-
operation: "create",
|
|
499
|
-
recordId: String(doc._id),
|
|
500
|
-
req: req,
|
|
501
|
-
verb: "created",
|
|
502
|
-
});
|
|
503
|
-
_a.label = 2;
|
|
504
|
-
case 2:
|
|
505
|
-
_a.trys.push([2, 4, , 5]);
|
|
506
|
-
return [4 /*yield*/, responseHandler(doc, "create", req, options)];
|
|
507
|
-
case 3:
|
|
508
|
-
serialized = _a.sent();
|
|
509
|
-
return [2 /*return*/, res.status(201).json({ data: serialized })];
|
|
510
|
-
case 4:
|
|
511
|
-
error_1 = _a.sent();
|
|
512
|
-
throw (0, errors_1.passthroughOrWrap)(error_1, {
|
|
513
|
-
code: "response-handler-error",
|
|
514
|
-
title: "responseHandler error",
|
|
515
|
-
});
|
|
516
|
-
case 5: return [2 /*return*/];
|
|
517
|
-
}
|
|
352
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
353
|
+
const { doc } = await (0, executors_1.executeCreate)({
|
|
354
|
+
body: req.body,
|
|
355
|
+
model,
|
|
356
|
+
options,
|
|
357
|
+
req,
|
|
358
|
+
user: req.user,
|
|
359
|
+
});
|
|
360
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
361
|
+
after: doc,
|
|
362
|
+
audit: options.audit,
|
|
363
|
+
modelName: model.modelName,
|
|
364
|
+
operation: "create",
|
|
365
|
+
recordId: String(doc._id),
|
|
366
|
+
req,
|
|
367
|
+
verb: "created",
|
|
518
368
|
});
|
|
519
|
-
|
|
369
|
+
try {
|
|
370
|
+
const serialized = await responseHandler(doc, "create", req, options);
|
|
371
|
+
return res.status(201).json({ data: serialized });
|
|
372
|
+
}
|
|
373
|
+
catch (error) {
|
|
374
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
375
|
+
code: "response-handler-error",
|
|
376
|
+
title: "responseHandler error",
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}));
|
|
520
380
|
router.get("/", [
|
|
521
381
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
522
382
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
523
383
|
(0, openApi_1.listOpenApiMiddleware)(model, options, routePath),
|
|
524
384
|
queryValidation,
|
|
525
|
-
], (0, exports.asyncHandler)(
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
385
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
386
|
+
let query = {};
|
|
387
|
+
for (const queryParam of Object.keys(options.defaultQueryParams ?? [])) {
|
|
388
|
+
query[queryParam] = options.defaultQueryParams?.[queryParam];
|
|
389
|
+
}
|
|
390
|
+
for (const queryParam of Object.keys(req.query)) {
|
|
391
|
+
if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
checkQueryParamAllowed(queryParam, req.query[queryParam], options.queryFields);
|
|
395
|
+
// Not sure if this is necessary or if mongoose does the right thing.
|
|
396
|
+
if (req.query[queryParam] === "true") {
|
|
397
|
+
query[queryParam] = true;
|
|
398
|
+
}
|
|
399
|
+
else if (req.query[queryParam] === "false") {
|
|
400
|
+
query[queryParam] = false;
|
|
401
|
+
}
|
|
402
|
+
else {
|
|
403
|
+
query[queryParam] = req.query[queryParam];
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
query = mergeDateRangeQueryParams(model, query);
|
|
407
|
+
// Special operators. NOTE: these request Mongo Atlas.
|
|
408
|
+
if (req.query.$search) {
|
|
409
|
+
mongoose_1.default.connection.db?.collection(model.collection.collectionName);
|
|
410
|
+
}
|
|
411
|
+
if (req.query.$autocomplete) {
|
|
412
|
+
mongoose_1.default.connection.db?.collection(model.collection.collectionName);
|
|
413
|
+
}
|
|
414
|
+
// Check if any of the keys in the query are not allowed by options.queryFilter
|
|
415
|
+
if (options.queryFilter) {
|
|
416
|
+
let queryFilter;
|
|
417
|
+
try {
|
|
418
|
+
queryFilter = await options.queryFilter(req.user, query);
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
422
|
+
code: "query-filter-error",
|
|
423
|
+
status: 400,
|
|
424
|
+
title: "Query filter error",
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
// If the query filter returns null specifically, we know this is a query that shouldn't
|
|
428
|
+
// return any results.
|
|
429
|
+
if (queryFilter === null) {
|
|
430
|
+
return res.json({ data: [] });
|
|
431
|
+
}
|
|
432
|
+
query = { ...query, ...queryFilter };
|
|
433
|
+
for (const [key, value] of Object.entries(queryFilter)) {
|
|
434
|
+
if (value === undefined) {
|
|
435
|
+
delete query[key];
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
let limit = options.defaultLimit ?? 100;
|
|
440
|
+
if (Number(req.query.limit)) {
|
|
441
|
+
limit = Math.min(Number(req.query.limit), options.maxLimit ?? 500);
|
|
442
|
+
}
|
|
443
|
+
if (query.period) {
|
|
444
|
+
// need to remove 'period' since it isn't part of any schemas but parsed and applied in
|
|
445
|
+
// queryFilter instead
|
|
446
|
+
query.period = undefined;
|
|
447
|
+
}
|
|
448
|
+
let builtQuery = model.find(query).limit(limit + 1);
|
|
449
|
+
const total = await model.countDocuments(query);
|
|
450
|
+
if (req.query.page) {
|
|
451
|
+
if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
|
|
452
|
+
throw new errors_1.BadRequestError({
|
|
453
|
+
code: "invalid-page",
|
|
454
|
+
detail: `Invalid page: ${req.query.page}`,
|
|
455
|
+
source: { parameter: "page" },
|
|
456
|
+
title: "Invalid page",
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
|
|
460
|
+
}
|
|
461
|
+
// Query param sort takes precedence over options.sort.
|
|
462
|
+
if (req.query.sort) {
|
|
463
|
+
builtQuery = builtQuery.sort(req.query.sort);
|
|
464
|
+
}
|
|
465
|
+
else if (options.sort) {
|
|
466
|
+
builtQuery = builtQuery.sort(options.sort);
|
|
467
|
+
}
|
|
468
|
+
const populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
|
|
469
|
+
let data;
|
|
470
|
+
try {
|
|
471
|
+
data = (await populatedQuery.exec());
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
475
|
+
code: "list-error",
|
|
476
|
+
title: "List error",
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
let serialized;
|
|
480
|
+
try {
|
|
481
|
+
serialized = await responseHandler(data, "list", req, options);
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
485
|
+
code: "response-handler-error",
|
|
486
|
+
title: "responseHandler error",
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
let more;
|
|
490
|
+
try {
|
|
491
|
+
if (serialized && Array.isArray(serialized)) {
|
|
492
|
+
more = serialized.length === limit + 1 && serialized.length > 0;
|
|
493
|
+
if (more) {
|
|
494
|
+
// Slice off the extra document we fetched to determine if more is true or not.
|
|
495
|
+
serialized = serialized.slice(0, limit);
|
|
496
|
+
if (!req.query.page) {
|
|
497
|
+
const msg = `More than ${limit} results returned for ${model.collection.name} without pagination, data may be silently truncated. req.query: ${JSON.stringify(req.query)}`;
|
|
498
|
+
logger_1.logger.warn(msg);
|
|
613
499
|
try {
|
|
614
|
-
|
|
500
|
+
Sentry.captureMessage(msg);
|
|
615
501
|
}
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
_s.label = 5;
|
|
619
|
-
case 5:
|
|
620
|
-
limit = (_q = options.defaultLimit) !== null && _q !== void 0 ? _q : 100;
|
|
621
|
-
if (Number(req.query.limit)) {
|
|
622
|
-
limit = Math.min(Number(req.query.limit), (_r = options.maxLimit) !== null && _r !== void 0 ? _r : 500);
|
|
623
|
-
}
|
|
624
|
-
if (query.period) {
|
|
625
|
-
// need to remove 'period' since it isn't part of any schemas but parsed and applied in
|
|
626
|
-
// queryFilter instead
|
|
627
|
-
query.period = undefined;
|
|
628
|
-
}
|
|
629
|
-
builtQuery = model.find(query).limit(limit + 1);
|
|
630
|
-
return [4 /*yield*/, model.countDocuments(query)];
|
|
631
|
-
case 6:
|
|
632
|
-
total = _s.sent();
|
|
633
|
-
if (req.query.page) {
|
|
634
|
-
if (Number(req.query.page) === 0 || Number.isNaN(Number(req.query.page))) {
|
|
635
|
-
throw new errors_1.BadRequestError({
|
|
636
|
-
code: "invalid-page",
|
|
637
|
-
detail: "Invalid page: ".concat(req.query.page),
|
|
638
|
-
source: { parameter: "page" },
|
|
639
|
-
title: "Invalid page",
|
|
640
|
-
});
|
|
641
|
-
}
|
|
642
|
-
builtQuery = builtQuery.skip((Number(req.query.page) - 1) * limit);
|
|
643
|
-
}
|
|
644
|
-
// Query param sort takes precedence over options.sort.
|
|
645
|
-
if (req.query.sort) {
|
|
646
|
-
builtQuery = builtQuery.sort(req.query.sort);
|
|
647
|
-
}
|
|
648
|
-
else if (options.sort) {
|
|
649
|
-
builtQuery = builtQuery.sort(options.sort);
|
|
650
|
-
}
|
|
651
|
-
populatedQuery = (0, exports.addPopulateToQuery)(builtQuery, options.populatePaths);
|
|
652
|
-
_s.label = 7;
|
|
653
|
-
case 7:
|
|
654
|
-
_s.trys.push([7, 9, , 10]);
|
|
655
|
-
return [4 /*yield*/, populatedQuery.exec()];
|
|
656
|
-
case 8:
|
|
657
|
-
data = (_s.sent());
|
|
658
|
-
return [3 /*break*/, 10];
|
|
659
|
-
case 9:
|
|
660
|
-
error_3 = _s.sent();
|
|
661
|
-
throw (0, errors_1.passthroughOrWrap)(error_3, {
|
|
662
|
-
code: "list-error",
|
|
663
|
-
title: "List error",
|
|
664
|
-
});
|
|
665
|
-
case 10:
|
|
666
|
-
_s.trys.push([10, 12, , 13]);
|
|
667
|
-
return [4 /*yield*/, responseHandler(data, "list", req, options)];
|
|
668
|
-
case 11:
|
|
669
|
-
serialized = _s.sent();
|
|
670
|
-
return [3 /*break*/, 13];
|
|
671
|
-
case 12:
|
|
672
|
-
error_4 = _s.sent();
|
|
673
|
-
throw (0, errors_1.passthroughOrWrap)(error_4, {
|
|
674
|
-
code: "response-handler-error",
|
|
675
|
-
title: "responseHandler error",
|
|
676
|
-
});
|
|
677
|
-
case 13:
|
|
678
|
-
try {
|
|
679
|
-
if (serialized && Array.isArray(serialized)) {
|
|
680
|
-
more = serialized.length === limit + 1 && serialized.length > 0;
|
|
681
|
-
if (more) {
|
|
682
|
-
// Slice off the extra document we fetched to determine if more is true or not.
|
|
683
|
-
serialized = serialized.slice(0, limit);
|
|
684
|
-
if (!req.query.page) {
|
|
685
|
-
msg = "More than ".concat(limit, " results returned for ").concat(model.collection.name, " without pagination, data may be silently truncated. req.query: ").concat(JSON.stringify(req.query));
|
|
686
|
-
logger_1.logger.warn(msg);
|
|
687
|
-
try {
|
|
688
|
-
Sentry.captureMessage(msg);
|
|
689
|
-
}
|
|
690
|
-
catch (error) {
|
|
691
|
-
logger_1.logger.error("Error capturing message: ".concat(error));
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
}
|
|
695
|
-
return [2 /*return*/, res.json({
|
|
696
|
-
data: serialized,
|
|
697
|
-
limit: limit,
|
|
698
|
-
more: more,
|
|
699
|
-
page: req.query.page,
|
|
700
|
-
total: total,
|
|
701
|
-
})];
|
|
502
|
+
catch (error) {
|
|
503
|
+
logger_1.logger.error(`Error capturing message: ${error}`);
|
|
702
504
|
}
|
|
703
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
704
|
-
}
|
|
705
|
-
catch (error) {
|
|
706
|
-
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
707
|
-
code: "serialization-error",
|
|
708
|
-
title: "Serialization error",
|
|
709
|
-
});
|
|
710
505
|
}
|
|
711
|
-
|
|
506
|
+
}
|
|
507
|
+
return res.json({
|
|
508
|
+
data: serialized,
|
|
509
|
+
limit,
|
|
510
|
+
more,
|
|
511
|
+
page: req.query.page,
|
|
512
|
+
total,
|
|
513
|
+
});
|
|
712
514
|
}
|
|
713
|
-
|
|
714
|
-
|
|
515
|
+
return res.json({ data: serialized });
|
|
516
|
+
}
|
|
517
|
+
catch (error) {
|
|
518
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
519
|
+
code: "serialization-error",
|
|
520
|
+
title: "Serialization error",
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
}));
|
|
715
524
|
router.get("/:id", [
|
|
716
525
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
717
526
|
(0, openApi_1.getOpenApiMiddleware)(model, options),
|
|
718
527
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
719
|
-
], (0, exports.asyncHandler)(
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
case 2:
|
|
730
|
-
serialized = _a.sent();
|
|
731
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
732
|
-
case 3:
|
|
733
|
-
error_5 = _a.sent();
|
|
734
|
-
throw (0, errors_1.passthroughOrWrap)(error_5, {
|
|
735
|
-
code: "response-handler-error",
|
|
736
|
-
title: "responseHandler error",
|
|
737
|
-
});
|
|
738
|
-
case 4: return [2 /*return*/];
|
|
739
|
-
}
|
|
740
|
-
});
|
|
741
|
-
}); }));
|
|
742
|
-
router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(function (_req, _res) { return __awaiter(void 0, void 0, void 0, function () {
|
|
743
|
-
return __generator(this, function (_a) {
|
|
744
|
-
// Patch is what we want 90% of the time
|
|
745
|
-
throw new errors_1.APIError({
|
|
746
|
-
code: "put-not-supported",
|
|
747
|
-
detail: "Use PATCH to update a document.",
|
|
748
|
-
title: "PUT is not supported.",
|
|
528
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
529
|
+
const data = req.obj;
|
|
530
|
+
try {
|
|
531
|
+
const serialized = await responseHandler(data, "read", req, options);
|
|
532
|
+
return res.json({ data: serialized });
|
|
533
|
+
}
|
|
534
|
+
catch (error) {
|
|
535
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
536
|
+
code: "response-handler-error",
|
|
537
|
+
title: "responseHandler error",
|
|
749
538
|
});
|
|
539
|
+
}
|
|
540
|
+
}));
|
|
541
|
+
router.put("/:id", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(async (_req, _res) => {
|
|
542
|
+
// Patch is what we want 90% of the time
|
|
543
|
+
throw new errors_1.APIError({
|
|
544
|
+
code: "put-not-supported",
|
|
545
|
+
detail: "Use PATCH to update a document.",
|
|
546
|
+
title: "PUT is not supported.",
|
|
750
547
|
});
|
|
751
|
-
})
|
|
548
|
+
}));
|
|
752
549
|
router.patch("/:id", [
|
|
753
550
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
754
551
|
(0, openApi_1.patchOpenApiMiddleware)(model, options),
|
|
755
552
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
756
553
|
updateValidation,
|
|
757
|
-
], (0, exports.asyncHandler)(
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
serialized = _a.sent();
|
|
816
|
-
return [2 /*return*/, res.status(409).json({
|
|
817
|
-
data: serialized,
|
|
818
|
-
error: "Conflict",
|
|
819
|
-
message: "Document was modified since your last read",
|
|
820
|
-
})];
|
|
821
|
-
case 5: throw error_6;
|
|
822
|
-
case 6:
|
|
823
|
-
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
824
|
-
after: doc,
|
|
825
|
-
audit: options.audit,
|
|
826
|
-
before: previous,
|
|
827
|
-
modelName: model.modelName,
|
|
828
|
-
operation: "update",
|
|
829
|
-
recordId: String(doc._id),
|
|
830
|
-
req: req,
|
|
831
|
-
verb: "updated",
|
|
832
|
-
});
|
|
833
|
-
_a.label = 7;
|
|
834
|
-
case 7:
|
|
835
|
-
_a.trys.push([7, 9, , 10]);
|
|
836
|
-
return [4 /*yield*/, responseHandler(doc, "update", req, options)];
|
|
837
|
-
case 8:
|
|
838
|
-
serialized = _a.sent();
|
|
839
|
-
return [2 /*return*/, res.json({ data: serialized })];
|
|
840
|
-
case 9:
|
|
841
|
-
error_7 = _a.sent();
|
|
842
|
-
throw (0, errors_1.passthroughOrWrap)(error_7, {
|
|
843
|
-
code: "response-handler-error",
|
|
844
|
-
title: "responseHandler error",
|
|
845
|
-
});
|
|
846
|
-
case 10: return [2 /*return*/];
|
|
554
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
555
|
+
const existingDoc = req
|
|
556
|
+
.obj;
|
|
557
|
+
// Read `_updatedAt` before the executor strips it from the body; the executor's
|
|
558
|
+
// conflict detection still runs after preUpdate, matching the previous inline order.
|
|
559
|
+
const bodyUpdatedAt = req.body._updatedAt;
|
|
560
|
+
const preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
|
|
561
|
+
const httpUnmodifiedSince = req.headers["if-unmodified-since"];
|
|
562
|
+
const timestampValue = Array.isArray(preciseUnmodifiedSince)
|
|
563
|
+
? preciseUnmodifiedSince[0]
|
|
564
|
+
: preciseUnmodifiedSince;
|
|
565
|
+
const httpTimestampValue = Array.isArray(httpUnmodifiedSince)
|
|
566
|
+
? httpUnmodifiedSince[0]
|
|
567
|
+
: httpUnmodifiedSince;
|
|
568
|
+
let concurrencyCheck;
|
|
569
|
+
if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
|
|
570
|
+
const usingPreciseHeader = Boolean(timestampValue);
|
|
571
|
+
const usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
|
|
572
|
+
const clientTimestamp = timestampValue
|
|
573
|
+
? luxon_1.DateTime.fromISO(timestampValue)
|
|
574
|
+
: httpTimestampValue
|
|
575
|
+
? luxon_1.DateTime.fromHTTP(httpTimestampValue)
|
|
576
|
+
: luxon_1.DateTime.fromISO(bodyUpdatedAt);
|
|
577
|
+
concurrencyCheck = {
|
|
578
|
+
// An unparseable value round-trips as an invalid Date; the executor turns it into
|
|
579
|
+
// the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
|
|
580
|
+
ifUnmodifiedSince: clientTimestamp.toJSDate(),
|
|
581
|
+
invalidTimestampDetail: usingPreciseHeader
|
|
582
|
+
? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
|
|
583
|
+
: usingHttpHeader
|
|
584
|
+
? "If-Unmodified-Since header could not be parsed as an HTTP date"
|
|
585
|
+
: "_updatedAt body field could not be parsed as an ISO date",
|
|
586
|
+
type: "timestamp",
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
let doc;
|
|
590
|
+
const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
|
|
591
|
+
try {
|
|
592
|
+
({ doc } = await (0, executors_1.executeUpdate)({
|
|
593
|
+
body: req.body,
|
|
594
|
+
concurrencyCheck,
|
|
595
|
+
existingDoc,
|
|
596
|
+
id: req.params.id,
|
|
597
|
+
model,
|
|
598
|
+
options,
|
|
599
|
+
req,
|
|
600
|
+
user: req.user,
|
|
601
|
+
}));
|
|
602
|
+
}
|
|
603
|
+
catch (error) {
|
|
604
|
+
// Duck-typed: `instanceof` breaks for Error subclasses in the compiled ES5 dist.
|
|
605
|
+
if ((0, executors_1.isExecutorConflictError)(error)) {
|
|
606
|
+
const serialized = await responseHandler(error.doc, "update", req, options);
|
|
607
|
+
return res.status(409).json({
|
|
608
|
+
data: serialized,
|
|
609
|
+
error: "Conflict",
|
|
610
|
+
message: "Document was modified since your last read",
|
|
611
|
+
});
|
|
847
612
|
}
|
|
613
|
+
throw error;
|
|
614
|
+
}
|
|
615
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
616
|
+
after: doc,
|
|
617
|
+
audit: options.audit,
|
|
618
|
+
before: previous,
|
|
619
|
+
modelName: model.modelName,
|
|
620
|
+
operation: "update",
|
|
621
|
+
recordId: String(doc._id),
|
|
622
|
+
req,
|
|
623
|
+
verb: "updated",
|
|
848
624
|
});
|
|
849
|
-
|
|
625
|
+
try {
|
|
626
|
+
const serialized = await responseHandler(doc, "update", req, options);
|
|
627
|
+
return res.json({ data: serialized });
|
|
628
|
+
}
|
|
629
|
+
catch (error) {
|
|
630
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
631
|
+
code: "response-handler-error",
|
|
632
|
+
title: "responseHandler error",
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
}));
|
|
850
636
|
router.delete("/:id", [
|
|
851
637
|
(0, auth_1.authenticateMiddleware)(options.allowAnonymous),
|
|
852
638
|
(0, openApi_1.deleteOpenApiMiddleware)(model, options),
|
|
853
639
|
(0, permissions_1.permissionMiddleware)(model, options),
|
|
854
|
-
], (0, exports.asyncHandler)(
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
model: model,
|
|
865
|
-
options: options,
|
|
866
|
-
req: req,
|
|
867
|
-
user: req.user,
|
|
868
|
-
})];
|
|
869
|
-
case 1:
|
|
870
|
-
_a.sent();
|
|
871
|
-
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
872
|
-
audit: options.audit,
|
|
873
|
-
before: previous,
|
|
874
|
-
modelName: model.modelName,
|
|
875
|
-
operation: "delete",
|
|
876
|
-
recordId: String(existingDoc._id),
|
|
877
|
-
req: req,
|
|
878
|
-
verb: "deleted",
|
|
879
|
-
});
|
|
880
|
-
return [2 /*return*/, res.status(204).json({})];
|
|
881
|
-
}
|
|
640
|
+
], (0, exports.asyncHandler)(async (req, res) => {
|
|
641
|
+
const existingDoc = req.obj;
|
|
642
|
+
const previous = (0, record_1.snapshotAuditBefore)({ audit: options.audit, doc: existingDoc });
|
|
643
|
+
await (0, executors_1.executeDelete)({
|
|
644
|
+
existingDoc,
|
|
645
|
+
id: req.params.id,
|
|
646
|
+
model,
|
|
647
|
+
options,
|
|
648
|
+
req,
|
|
649
|
+
user: req.user,
|
|
882
650
|
});
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
case 1:
|
|
892
|
-
// TODO Combine array operations and .patch(), as they are very similar.
|
|
893
|
-
if (!(_d.sent())) {
|
|
894
|
-
throw new errors_1.APIError({
|
|
895
|
-
code: "array-update-not-allowed",
|
|
896
|
-
detail: "Access to PATCH on ".concat(model.modelName, " denied for ").concat((_b = req.user) === null || _b === void 0 ? void 0 : _b.id),
|
|
897
|
-
meta: { method: "PATCH", model: model.modelName },
|
|
898
|
-
status: 405,
|
|
899
|
-
title: "Access denied",
|
|
900
|
-
});
|
|
901
|
-
}
|
|
902
|
-
return [4 /*yield*/, model.findById(req.params.id)];
|
|
903
|
-
case 2:
|
|
904
|
-
doc = _d.sent();
|
|
905
|
-
prevDoc = (0, cloneDeep_1.default)(doc);
|
|
906
|
-
if (!doc) {
|
|
907
|
-
throw new errors_1.NotFoundError({
|
|
908
|
-
code: "document-not-found",
|
|
909
|
-
detail: "Could not find document to PATCH: ".concat(req.params.id),
|
|
910
|
-
meta: { model: model.modelName },
|
|
911
|
-
title: "Document not found",
|
|
912
|
-
});
|
|
913
|
-
}
|
|
914
|
-
return [4 /*yield*/, (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc)];
|
|
915
|
-
case 3:
|
|
916
|
-
if (!(_d.sent())) {
|
|
917
|
-
throw new errors_1.ForbiddenError({
|
|
918
|
-
code: "update-not-allowed",
|
|
919
|
-
detail: "Patch not allowed for user ".concat((_c = req.user) === null || _c === void 0 ? void 0 : _c.id, " on doc ").concat(doc._id),
|
|
920
|
-
meta: { model: model.modelName },
|
|
921
|
-
title: "Update not allowed",
|
|
922
|
-
});
|
|
923
|
-
}
|
|
924
|
-
field = req.params.field;
|
|
925
|
-
itemId = req.params.itemId;
|
|
926
|
-
// We apply the operation *before* the hooks. As far as the callers are concerned, this should
|
|
927
|
-
// be like PATCHing the field and replacing the whole thing.
|
|
928
|
-
if (operation !== "DELETE" && req.body[field] === undefined) {
|
|
929
|
-
throw new errors_1.BadRequestError({
|
|
930
|
-
code: "malformed-array-operation-body",
|
|
931
|
-
detail: "Malformed body, array operations should have a single, top level key, got: ".concat(Object.keys(req.body).join(",")),
|
|
932
|
-
meta: { field: field },
|
|
933
|
-
title: "Malformed array operation body",
|
|
934
|
-
});
|
|
935
|
-
}
|
|
936
|
-
array = __spreadArray([], __read(doc[field]), false);
|
|
937
|
-
if (operation === "POST") {
|
|
938
|
-
array.push(req.body[field]);
|
|
939
|
-
}
|
|
940
|
-
else if (operation === "PATCH" || operation === "DELETE") {
|
|
941
|
-
index = void 0;
|
|
942
|
-
if ((0, utils_1.isValidObjectId)(itemId)) {
|
|
943
|
-
index = array.findIndex(function (x) { return (x === null || x === void 0 ? void 0 : x.id) === itemId; });
|
|
944
|
-
}
|
|
945
|
-
else {
|
|
946
|
-
index = array.indexOf(itemId);
|
|
947
|
-
}
|
|
948
|
-
if (index === -1) {
|
|
949
|
-
throw new errors_1.NotFoundError({
|
|
950
|
-
code: "array-item-not-found",
|
|
951
|
-
detail: "Could not find ".concat(field, "/").concat(itemId),
|
|
952
|
-
meta: { field: field, itemId: itemId },
|
|
953
|
-
title: "Array item not found",
|
|
954
|
-
});
|
|
955
|
-
}
|
|
956
|
-
// For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
|
|
957
|
-
// other parts of the subdocument.
|
|
958
|
-
if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
|
|
959
|
-
Object.assign(array[index], req.body[field]);
|
|
960
|
-
}
|
|
961
|
-
else if (operation === "PATCH") {
|
|
962
|
-
// For PATCHing a string array, we can replace the whole object.
|
|
963
|
-
array[index] = req.body[field];
|
|
964
|
-
}
|
|
965
|
-
else {
|
|
966
|
-
array.splice(index, 1);
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
else {
|
|
970
|
-
throw new errors_1.BadRequestError({
|
|
971
|
-
code: "invalid-array-operation",
|
|
972
|
-
detail: "Invalid array operation: ".concat(operation),
|
|
973
|
-
meta: { operation: operation },
|
|
974
|
-
title: "Invalid array operation",
|
|
975
|
-
});
|
|
976
|
-
}
|
|
977
|
-
body = (_a = {}, _a[field] = array, _a);
|
|
978
|
-
try {
|
|
979
|
-
body = (0, transformers_1.transform)(options, body, "update", req.user);
|
|
980
|
-
}
|
|
981
|
-
catch (error) {
|
|
982
|
-
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
983
|
-
code: "transform-error",
|
|
984
|
-
status: 403,
|
|
985
|
-
title: "Transform error",
|
|
986
|
-
});
|
|
987
|
-
}
|
|
988
|
-
if (!options.preUpdate) return [3 /*break*/, 8];
|
|
989
|
-
_d.label = 4;
|
|
990
|
-
case 4:
|
|
991
|
-
_d.trys.push([4, 6, , 7]);
|
|
992
|
-
return [4 /*yield*/, options.preUpdate(body, req)];
|
|
993
|
-
case 5:
|
|
994
|
-
body = _d.sent();
|
|
995
|
-
return [3 /*break*/, 7];
|
|
996
|
-
case 6:
|
|
997
|
-
error_8 = _d.sent();
|
|
998
|
-
throw (0, errors_1.passthroughOrWrap)(error_8, {
|
|
999
|
-
code: "pre-update-hook-error",
|
|
1000
|
-
detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_8)),
|
|
1001
|
-
status: 400,
|
|
1002
|
-
title: "preUpdate hook error",
|
|
1003
|
-
});
|
|
1004
|
-
case 7:
|
|
1005
|
-
if (body === undefined) {
|
|
1006
|
-
throw new errors_1.ForbiddenError({
|
|
1007
|
-
code: "update-not-allowed",
|
|
1008
|
-
detail: "A body must be returned from preUpdate",
|
|
1009
|
-
title: "Update not allowed",
|
|
1010
|
-
});
|
|
1011
|
-
}
|
|
1012
|
-
if (body === null) {
|
|
1013
|
-
throw new errors_1.ForbiddenError({
|
|
1014
|
-
code: "update-not-allowed",
|
|
1015
|
-
detail: "preUpdate hook on ".concat(req.params.id, " returned null"),
|
|
1016
|
-
title: "Update not allowed",
|
|
1017
|
-
});
|
|
1018
|
-
}
|
|
1019
|
-
_d.label = 8;
|
|
1020
|
-
case 8:
|
|
1021
|
-
body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
|
|
1022
|
-
if (!(options.access && options.accessControl && body && typeof body === "object")) return [3 /*break*/, 10];
|
|
1023
|
-
return [4 /*yield*/, (0, modelRouterAccess_1.validateAccessWriteBody)({
|
|
1024
|
-
access: options.access,
|
|
1025
|
-
accessControl: options.accessControl,
|
|
1026
|
-
body: body,
|
|
1027
|
-
doc: doc,
|
|
1028
|
-
phase: "write",
|
|
1029
|
-
user: req.user,
|
|
1030
|
-
})];
|
|
1031
|
-
case 9:
|
|
1032
|
-
_d.sent();
|
|
1033
|
-
_d.label = 10;
|
|
1034
|
-
case 10:
|
|
1035
|
-
_d.trys.push([10, 12, , 13]);
|
|
1036
|
-
Object.assign(doc, body);
|
|
1037
|
-
return [4 /*yield*/, doc.save()];
|
|
1038
|
-
case 11:
|
|
1039
|
-
_d.sent();
|
|
1040
|
-
return [3 /*break*/, 13];
|
|
1041
|
-
case 12:
|
|
1042
|
-
error_9 = _d.sent();
|
|
1043
|
-
throw (0, errors_1.passthroughOrWrapWrite)(error_9, {
|
|
1044
|
-
code: "update-save-error",
|
|
1045
|
-
detail: "PATCH Pre Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_9)),
|
|
1046
|
-
status: 400,
|
|
1047
|
-
title: "PATCH Pre Update error",
|
|
1048
|
-
});
|
|
1049
|
-
case 13:
|
|
1050
|
-
if (!options.postUpdate) return [3 /*break*/, 17];
|
|
1051
|
-
_d.label = 14;
|
|
1052
|
-
case 14:
|
|
1053
|
-
_d.trys.push([14, 16, , 17]);
|
|
1054
|
-
return [4 /*yield*/, options.postUpdate(doc, body, req, prevDoc)];
|
|
1055
|
-
case 15:
|
|
1056
|
-
_d.sent();
|
|
1057
|
-
return [3 /*break*/, 17];
|
|
1058
|
-
case 16:
|
|
1059
|
-
error_10 = _d.sent();
|
|
1060
|
-
throw (0, errors_1.passthroughOrWrap)(error_10, {
|
|
1061
|
-
code: "post-update-hook-error",
|
|
1062
|
-
detail: "PATCH Post Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_10)),
|
|
1063
|
-
status: 400,
|
|
1064
|
-
title: "PATCH Post Update error",
|
|
1065
|
-
});
|
|
1066
|
-
case 17:
|
|
1067
|
-
arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
|
|
1068
|
-
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
1069
|
-
after: doc,
|
|
1070
|
-
audit: options.audit,
|
|
1071
|
-
before: prevDoc,
|
|
1072
|
-
modelName: model.modelName,
|
|
1073
|
-
operation: arrayAuditOperation,
|
|
1074
|
-
recordId: String(doc._id),
|
|
1075
|
-
req: req,
|
|
1076
|
-
verb: "updated",
|
|
1077
|
-
});
|
|
1078
|
-
return [2 /*return*/, res.json({
|
|
1079
|
-
data: (0, transformers_1.serialize)(req, options, doc),
|
|
1080
|
-
})];
|
|
1081
|
-
}
|
|
1082
|
-
});
|
|
1083
|
-
}); };
|
|
1084
|
-
var arrayPost = function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
|
|
1085
|
-
return __generator(this, function (_a) {
|
|
1086
|
-
return [2 /*return*/, arrayOperation(req, res, "POST")];
|
|
651
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
652
|
+
audit: options.audit,
|
|
653
|
+
before: previous,
|
|
654
|
+
modelName: model.modelName,
|
|
655
|
+
operation: "delete",
|
|
656
|
+
recordId: String(existingDoc._id),
|
|
657
|
+
req,
|
|
658
|
+
verb: "deleted",
|
|
1087
659
|
});
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
660
|
+
return res.status(204).json({});
|
|
661
|
+
}));
|
|
662
|
+
/**
|
|
663
|
+
* Applies consumer update transforms and authorization hooks for array subroutes.
|
|
664
|
+
* Keeping this pipeline shared ensures invalid field requests cannot bypass consumer
|
|
665
|
+
* authorization before modelRouter returns its own validation error.
|
|
666
|
+
*/
|
|
667
|
+
const applyArrayOperationUpdateHooks = async (inputBody, req) => {
|
|
668
|
+
let body = inputBody;
|
|
669
|
+
try {
|
|
670
|
+
body = (0, transformers_1.transform)(options, body, "update", req.user);
|
|
671
|
+
}
|
|
672
|
+
catch (error) {
|
|
673
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
674
|
+
code: "transform-error",
|
|
675
|
+
status: 403,
|
|
676
|
+
title: "Transform error",
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
if (options.preUpdate) {
|
|
680
|
+
try {
|
|
681
|
+
body = await options.preUpdate(body, req);
|
|
682
|
+
}
|
|
683
|
+
catch (error) {
|
|
684
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
685
|
+
code: "pre-update-hook-error",
|
|
686
|
+
detail: `preUpdate hook error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
687
|
+
status: 400,
|
|
688
|
+
title: "preUpdate hook error",
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
if (body === undefined) {
|
|
692
|
+
throw new errors_1.ForbiddenError({
|
|
693
|
+
code: "update-not-allowed",
|
|
694
|
+
detail: "A body must be returned from preUpdate",
|
|
695
|
+
title: "Update not allowed",
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
if (body === null) {
|
|
699
|
+
throw new errors_1.ForbiddenError({
|
|
700
|
+
code: "update-not-allowed",
|
|
701
|
+
detail: `preUpdate hook on ${req.params.id} returned null`,
|
|
702
|
+
title: "Update not allowed",
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
return body;
|
|
707
|
+
};
|
|
708
|
+
const arrayOperation = async (req, res, operation) => {
|
|
709
|
+
// TODO Combine array operations and .patch(), as they are very similar.
|
|
710
|
+
if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user))) {
|
|
711
|
+
throw new errors_1.APIError({
|
|
712
|
+
code: "array-update-not-allowed",
|
|
713
|
+
detail: `Access to PATCH on ${model.modelName} denied for ${req.user?.id}`,
|
|
714
|
+
meta: { method: "PATCH", model: model.modelName },
|
|
715
|
+
status: 405,
|
|
716
|
+
title: "Access denied",
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
const doc = await model.findById(req.params.id);
|
|
720
|
+
// Make a copy for passing pre-saved values to hooks.
|
|
721
|
+
const prevDoc = (0, cloneDeep_1.default)(doc);
|
|
722
|
+
if (!doc) {
|
|
723
|
+
throw new errors_1.NotFoundError({
|
|
724
|
+
code: "document-not-found",
|
|
725
|
+
detail: `Could not find document to PATCH: ${req.params.id}`,
|
|
726
|
+
meta: { model: model.modelName },
|
|
727
|
+
title: "Document not found",
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
if (!(await (0, permissions_1.checkPermissions)("update", options.permissions.update, req.user, doc))) {
|
|
731
|
+
throw new errors_1.ForbiddenError({
|
|
732
|
+
code: "update-not-allowed",
|
|
733
|
+
detail: `Patch not allowed for user ${req.user?.id} on doc ${doc._id}`,
|
|
734
|
+
meta: { model: model.modelName },
|
|
735
|
+
title: "Update not allowed",
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
const field = req.params.field;
|
|
739
|
+
const itemId = req.params.itemId;
|
|
740
|
+
// We apply the operation *before* the hooks. As far as the callers are concerned, this should
|
|
741
|
+
// be like PATCHing the field and replacing the whole thing.
|
|
742
|
+
if (operation !== "DELETE" && req.body[field] === undefined) {
|
|
743
|
+
throw new errors_1.BadRequestError({
|
|
744
|
+
code: "malformed-array-operation-body",
|
|
745
|
+
detail: `Malformed body, array operations should have a single, top level key, got: ${Object.keys(req.body).join(",")}`,
|
|
746
|
+
meta: { field },
|
|
747
|
+
title: "Malformed array operation body",
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
const currentFieldValue = doc[field];
|
|
751
|
+
if (!Array.isArray(currentFieldValue)) {
|
|
752
|
+
await applyArrayOperationUpdateHooks(req.body, req);
|
|
753
|
+
throw new errors_1.BadRequestError({
|
|
754
|
+
code: "array-operation-field-not-array",
|
|
755
|
+
detail: `Cannot apply an array operation to non-array field ${field}`,
|
|
756
|
+
meta: { field },
|
|
757
|
+
title: "Array operation field is not an array",
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
const array = [...currentFieldValue];
|
|
761
|
+
if (operation === "POST") {
|
|
762
|
+
array.push(req.body[field]);
|
|
763
|
+
}
|
|
764
|
+
else if (operation === "PATCH" || operation === "DELETE") {
|
|
765
|
+
// Check for subschema vs String array:
|
|
766
|
+
let index;
|
|
767
|
+
if ((0, utils_1.isValidObjectId)(itemId)) {
|
|
768
|
+
index = array.findIndex((x) => x?.id === itemId);
|
|
769
|
+
}
|
|
770
|
+
else {
|
|
771
|
+
index = array.indexOf(itemId);
|
|
772
|
+
}
|
|
773
|
+
if (index === -1) {
|
|
774
|
+
throw new errors_1.NotFoundError({
|
|
775
|
+
code: "array-item-not-found",
|
|
776
|
+
detail: `Could not find ${field}/${itemId}`,
|
|
777
|
+
meta: { field, itemId },
|
|
778
|
+
title: "Array item not found",
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
// For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
|
|
782
|
+
// other parts of the subdocument.
|
|
783
|
+
if (operation === "PATCH" && (0, utils_1.isValidObjectId)(itemId)) {
|
|
784
|
+
Object.assign(array[index], req.body[field]);
|
|
785
|
+
}
|
|
786
|
+
else if (operation === "PATCH") {
|
|
787
|
+
// For PATCHing a string array, we can replace the whole object.
|
|
788
|
+
array[index] = req.body[field];
|
|
789
|
+
}
|
|
790
|
+
else {
|
|
791
|
+
array.splice(index, 1);
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
else {
|
|
795
|
+
throw new errors_1.BadRequestError({
|
|
796
|
+
code: "invalid-array-operation",
|
|
797
|
+
detail: `Invalid array operation: ${operation}`,
|
|
798
|
+
meta: { operation },
|
|
799
|
+
title: "Invalid array operation",
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
let body = await applyArrayOperationUpdateHooks({ [field]: array }, req);
|
|
803
|
+
body = (0, auth_1.omitUserRolesFromWriteBody)(model.modelName, options.accessControl, body, req.terrenoAllowUserAdminWrite === true);
|
|
804
|
+
if (options.access && options.accessControl && body && typeof body === "object") {
|
|
805
|
+
await (0, modelRouterAccess_1.validateAccessWriteBody)({
|
|
806
|
+
access: options.access,
|
|
807
|
+
accessControl: options.accessControl,
|
|
808
|
+
body: body,
|
|
809
|
+
doc,
|
|
810
|
+
phase: "write",
|
|
811
|
+
user: req.user,
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
// Using .save here runs the risk of a versioning error if you try to make two simultaneous
|
|
815
|
+
// updates. We won't wind up with corrupted data, just an API error.
|
|
816
|
+
try {
|
|
817
|
+
Object.assign(doc, body);
|
|
818
|
+
await doc.save();
|
|
819
|
+
}
|
|
820
|
+
catch (error) {
|
|
821
|
+
throw (0, errors_1.passthroughOrWrapWrite)(error, {
|
|
822
|
+
code: "update-save-error",
|
|
823
|
+
detail: `PATCH Pre Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
824
|
+
status: 400,
|
|
825
|
+
title: "PATCH Pre Update error",
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
if (options.postUpdate) {
|
|
829
|
+
try {
|
|
830
|
+
await options.postUpdate(doc, body, req, prevDoc);
|
|
831
|
+
}
|
|
832
|
+
catch (error) {
|
|
833
|
+
throw (0, errors_1.passthroughOrWrap)(error, {
|
|
834
|
+
code: "post-update-hook-error",
|
|
835
|
+
detail: `PATCH Post Update error on ${req.params.id}: ${(0, errors_1.errorDetail)(error)}`,
|
|
836
|
+
status: 400,
|
|
837
|
+
title: "PATCH Post Update error",
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
const arrayAuditOperation = operation === "POST" ? "arrayPush" : operation === "PATCH" ? "arrayUpdate" : "arrayRemove";
|
|
842
|
+
void (0, record_1.maybeRecordModelRouterAudit)({
|
|
843
|
+
after: doc,
|
|
844
|
+
audit: options.audit,
|
|
845
|
+
before: prevDoc,
|
|
846
|
+
modelName: model.modelName,
|
|
847
|
+
operation: arrayAuditOperation,
|
|
848
|
+
recordId: String(doc._id),
|
|
849
|
+
req,
|
|
850
|
+
verb: "updated",
|
|
1092
851
|
});
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
return __generator(this, function (_a) {
|
|
1096
|
-
return [2 /*return*/, arrayOperation(req, res, "DELETE")];
|
|
852
|
+
return res.json({
|
|
853
|
+
data: (0, transformers_1.serialize)(req, options, doc),
|
|
1097
854
|
});
|
|
1098
|
-
}
|
|
855
|
+
};
|
|
856
|
+
const arrayPost = async (req, res) => {
|
|
857
|
+
return arrayOperation(req, res, "POST");
|
|
858
|
+
};
|
|
859
|
+
const arrayPatch = async (req, res) => {
|
|
860
|
+
return arrayOperation(req, res, "PATCH");
|
|
861
|
+
};
|
|
862
|
+
const arrayDelete = async (req, res) => {
|
|
863
|
+
return arrayOperation(req, res, "DELETE");
|
|
864
|
+
};
|
|
1099
865
|
// Set up routes for managing array fields. Check if there any array fields to add this for.
|
|
1100
|
-
if (Object.values(model.schema.paths).find(
|
|
866
|
+
if (Object.values(model.schema.paths).find((config) => config.instance === "Array")) {
|
|
1101
867
|
router.post("/:id/:field", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPost));
|
|
1102
868
|
router.patch("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayPatch));
|
|
1103
869
|
router.delete("/:id/:field/:itemId", (0, auth_1.authenticateMiddleware)(options.allowAnonymous), (0, exports.asyncHandler)(arrayDelete));
|
|
@@ -1105,20 +871,19 @@ var _buildModelRouter = function (model, options, routePath) {
|
|
|
1105
871
|
router.use(errors_1.apiErrorMiddleware);
|
|
1106
872
|
return router;
|
|
1107
873
|
};
|
|
1108
|
-
|
|
1109
|
-
var _a, _b;
|
|
874
|
+
const asyncHandler = (fn, options) => {
|
|
1110
875
|
// If no validation options, return simple handler
|
|
1111
|
-
if (!
|
|
1112
|
-
return
|
|
876
|
+
if (!options?.bodySchema && !options?.querySchema) {
|
|
877
|
+
return (req, res, next) => {
|
|
1113
878
|
return Promise.resolve(fn(req, res, next)).catch(next);
|
|
1114
879
|
};
|
|
1115
880
|
}
|
|
1116
881
|
// Import validation functions dynamically to avoid circular deps at module load
|
|
1117
|
-
|
|
882
|
+
const { validateRequestBody, validateQueryParams, getOpenApiValidatorConfig, } = require("./openApiValidator");
|
|
1118
883
|
// Build validation middleware
|
|
1119
|
-
|
|
884
|
+
const validators = [];
|
|
1120
885
|
// Determine if validation should be enabled
|
|
1121
|
-
|
|
886
|
+
const shouldValidate = options.validate ?? getOpenApiValidatorConfig().validateRequests ?? false;
|
|
1122
887
|
if (shouldValidate) {
|
|
1123
888
|
if (options.bodySchema) {
|
|
1124
889
|
validators.push(validateRequestBody(options.bodySchema, { enabled: true }));
|
|
@@ -1127,16 +892,16 @@ var asyncHandler = function (fn, options) {
|
|
|
1127
892
|
validators.push(validateQueryParams(options.querySchema, { enabled: true }));
|
|
1128
893
|
}
|
|
1129
894
|
}
|
|
1130
|
-
return
|
|
895
|
+
return (req, res, next) => {
|
|
1131
896
|
// Run validators sequentially, then the handler
|
|
1132
|
-
|
|
897
|
+
const runValidators = (index) => {
|
|
1133
898
|
if (index >= validators.length) {
|
|
1134
899
|
// All validators passed, run the actual handler
|
|
1135
900
|
Promise.resolve(fn(req, res, next)).catch(next);
|
|
1136
901
|
return;
|
|
1137
902
|
}
|
|
1138
903
|
try {
|
|
1139
|
-
validators[index](req, res, (
|
|
904
|
+
validators[index](req, res, ((err) => {
|
|
1140
905
|
if (err) {
|
|
1141
906
|
next(err);
|
|
1142
907
|
return;
|