-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathinjectModel.js
More file actions
executable file
·331 lines (280 loc) · 9.08 KB
/
Copy pathinjectModel.js
File metadata and controls
executable file
·331 lines (280 loc) · 9.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
const modelRegistry = new WeakMap();
const mongoose = require("mongoose");
const { UNIQUE_SUPPORTED_TYPES_SET } = require("./schema.constants");
const typeMapping = {
String: String,
Number: Number,
Boolean: Boolean,
Date: Date,
};
// Recursive field definition builder
// Recursive field definition builder
function buildFieldDef(field, projectId, isExternal, isUsersCollection = false) {
// Object type — nested sub-schema
if (field.type === "Object" && field.fields && field.fields.length > 0) {
const subSchema = {};
field.fields.forEach((f) => {
const normalizedKey = normalizeKey(f.key);
if (!normalizedKey) return;
subSchema[normalizedKey] = buildFieldDef(f, projectId, isExternal, isUsersCollection);
});
return { type: subSchema, required: !!field.required };
}
// Array type
if (field.type === "Array") {
if (!field.items) {
return {
type: [mongoose.Schema.Types.Mixed],
required: !!field.required,
};
}
// Array of Objects
if (
field.items.type === "Object" &&
field.items.fields &&
field.items.fields.length > 0
) {
const subSchema = {};
field.items.fields.forEach((f) => {
const normalizedKey = normalizeKey(f.key);
if (!normalizedKey) return;
subSchema[normalizedKey] = buildFieldDef(f, projectId, isExternal, isUsersCollection);
});
return { type: [subSchema], required: !!field.required };
}
// Array of Ref
if (field.items && field.items.type === "Ref") {
const targetRef = isExternal ? field.items.ref : `${projectId}_${field.items.ref}`;
return {
type: [{ type: mongoose.Schema.Types.ObjectId, ref: targetRef }],
required: !!field.required,
};
}
// Array of primitives
const itemType =
typeMapping[field.items.type] || mongoose.Schema.Types.Mixed;
return { type: [itemType], required: !!field.required };
}
// Ref type — stores ObjectId
if (field.type === "Ref") {
const targetRef = isExternal ? field.ref : `${projectId}_${field.ref}`;
return {
type: mongoose.Schema.Types.ObjectId,
ref: targetRef,
required: !!field.required,
};
}
// Primitive types
const def = {
type: typeMapping[field.type],
required: !!field.required,
};
// pass default through when defined
if (field.default !== undefined) {
def.default = field.default;
}
// HARDEN: Exclude password by default for project users
if (isUsersCollection && normalizeKey(field.key) === "password") {
def.select = false;
}
return def;
}
function normalizeKey(key) {
return String(key || "")
.replace(/\uFEFF/g, "")
.trim();
}
function buildMongooseSchema(fieldsArray = [], projectId, isExternal, isUsersCollection = false) {
const schemaDef = {};
fieldsArray.forEach((field) => {
const normalizedKey = normalizeKey(field.key);
if (!normalizedKey) return;
schemaDef[normalizedKey] = buildFieldDef(field, projectId, isExternal, isUsersCollection);
});
// Explicitly add soft-delete fields to ensure schema consistency on inserts
schemaDef.isDeleted = { type: Boolean, default: false };
schemaDef.deletedAt = { type: Date, default: null };
const schema = new mongoose.Schema(schemaDef, {
timestamps: true,
strict: false,
});
// Compound index to optimize the daily trash cleanup worker
schema.index({ isDeleted: 1, deletedAt: 1 });
return schema;
}
function getCompiledModel(connection, collectionData, projectId, isExternal) {
let collectionName = "";
if (!isExternal) {
collectionName = `${projectId}_${collectionData.name}`;
} else {
collectionName = collectionData.name;
}
// Get per-connection cache
if (!modelRegistry.has(connection)) {
modelRegistry.set(connection, new Map());
}
const connectionModels = modelRegistry.get(connection);
// If already compiled for THIS connection
if (connectionModels.has(collectionName)) {
return connectionModels.get(collectionName);
}
// If model already exists on connection (edge case)
if (connection.models[collectionName]) {
const existingModel = connection.models[collectionName];
connectionModels.set(collectionName, existingModel);
return existingModel;
}
// Build schema + compile
const isUsersCollection = collectionData.name === "users";
const schema = buildMongooseSchema(collectionData.model, projectId, isExternal, isUsersCollection);
const model = connection.model(collectionName, schema);
// Cache it
connectionModels.set(collectionName, model);
return model;
}
// Clear cached model (needed when schema changes)
function clearCompiledModel(connection, collectionName) {
if (modelRegistry.has(connection)) {
modelRegistry.get(connection).delete(collectionName);
}
if (connection.models[collectionName]) {
delete connection.models[collectionName];
}
}
function getUniqueFieldFilter(fieldKey, isRequired) {
if (isRequired) {
return {}; // scan ALL docs, including those missing the field
}
return { [fieldKey]: { $exists: true, $ne: null } };
}
async function findDuplicates(Model, fieldKey, isRequired) {
return Model.aggregate([
{
$match: getUniqueFieldFilter(fieldKey, isRequired),
},
{
$group: {
_id: `$${fieldKey}`,
count: { $sum: 1 },
},
},
{
$match: {
count: { $gt: 1 },
},
},
]);
}
async function safeDropIndex(Model, name) {
try {
await Model.collection.dropIndex(name);
} catch (err) {
if (err.code !== 27 && !/index not found/i.test(err.message) && !/does not exist/i.test(err.message)) {
throw err;
}
}
}
async function createUniqueIndexes(Model, fields = []) {
const createdIndexes = [];
let existingIndexes = [];
try {
existingIndexes = await Model.collection.indexes();
} catch (err) {
if (err.code !== 26 && !/ns does not exist/i.test(err.message)) {
throw err;
}
}
const existingIndexNames = new Set(existingIndexes.map((idx) => idx.name));
const schemaUniqueKeys = new Set();
for (const field of fields) {
if (field.unique && UNIQUE_SUPPORTED_TYPES_SET.has(field.type)) {
const nk = normalizeKey(field.key);
if (nk) {
schemaUniqueKeys.add(`unique_${nk}_1`);
}
}
}
// Pre-validate duplicates for all fields requiring index creation or recreation to leave existing indexes untouched on failure
for (const field of fields) {
if (!field.unique) continue;
if (!UNIQUE_SUPPORTED_TYPES_SET.has(field.type)) continue;
const normalizedKey = normalizeKey(field.key);
if (!normalizedKey) continue;
const indexName = `unique_${normalizedKey}_1`;
const existingIndex = existingIndexes.find((idx) => idx.name === indexName);
if (existingIndex) {
const isExistingPartial = !!existingIndex.partialFilterExpression;
const isDesiredPartial = !field.required;
if (isExistingPartial === isDesiredPartial) {
continue;
}
}
const duplicates = await findDuplicates(
Model,
normalizedKey,
!!field.required,
);
if (duplicates.length > 0) {
const examples = duplicates
.slice(0, 3)
.map((d) => JSON.stringify(d._id))
.join(", ");
throw new Error(
`Cannot create unique index on '${normalizedKey}'. ${duplicates.length} duplicate values exist.${examples ? ` Examples: ${examples}` : ""}`,
);
}
}
try {
for (const field of fields) {
if (!field.unique) continue;
if (!UNIQUE_SUPPORTED_TYPES_SET.has(field.type)) continue;
const normalizedKey = normalizeKey(field.key);
if (!normalizedKey) continue;
const indexName = `unique_${normalizedKey}_1`;
const existingIndex = existingIndexes.find((idx) => idx.name === indexName);
if (existingIndex) {
const isExistingPartial = !!existingIndex.partialFilterExpression;
const isDesiredPartial = !field.required;
if (isExistingPartial !== isDesiredPartial) {
await safeDropIndex(Model, indexName);
existingIndexNames.delete(indexName);
} else {
continue;
}
}
const indexOptions = {
unique: true,
name: indexName,
};
if (!field.required) {
indexOptions.partialFilterExpression = {
[normalizedKey]: { $exists: true, $ne: null },
};
}
const createdName = await Model.collection.createIndex(
{ [normalizedKey]: 1 },
indexOptions,
);
if (!existingIndexNames.has(createdName)) {
createdIndexes.push(createdName);
}
}
// Drop stale unique indexes ONLY after all index creation/validation succeeds
for (const index of existingIndexes) {
const name = index.name;
if (name.startsWith("unique_") && name.endsWith("_1") && !schemaUniqueKeys.has(name)) {
await safeDropIndex(Model, name);
}
}
} catch (err) {
for (const indexName of createdIndexes) {
await safeDropIndex(Model, indexName).catch(() => {});
}
throw err;
}
}
module.exports = {
getCompiledModel,
clearCompiledModel,
createUniqueIndexes,
};