-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathmodel-helper.js
366 lines (332 loc) Β· 12.2 KB
/
model-helper.js
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
'use strict';
let config = require("../config");
const _ = require('lodash');
//TODO: allow "unique" field to be rest-hapi specific if soft deletes are enabled (i.e. implement a unique constraint based on the required field and the "isDeleted" flag)
//TODO: correctly label "model" and "schema" files and objects throughout project
//TODO: Limiting the populated fields could also be accomplished with the "select" parameter of the "populate" function.
const internals = {};
/**
* Create a mongoose model with the given Schema and collectionName after adding optional metadata fields
* @param Schema: A mongoose schema object.
* @returns {*}: The resulting mongoose model.
*/
internals.createModel = function(Schema, mongoose) {
const Types = mongoose.Schema.Types;
//TODO: require createdAt and updatedAt
if (Schema.statics.collectionName !== 'auditLog') {
if (config.enableCreatedAt) {
let createdAt = {
createdAt: {
type: Types.Date,
allowOnCreate: false,
allowOnUpdate: false
}
};
Schema.add(createdAt);
}
if (config.enableUpdatedAt) {
let updatedAt = {
updatedAt: {
type: Types.Date,
allowOnCreate: false,
allowOnUpdate: false
}
};
Schema.add(updatedAt);
}
if (config.enableDeletedAt) {
let deletedAt = {
deletedAt: {
type: Types.Date,
allowOnCreate: false,
allowOnUpdate: false,
}
};
Schema.add(deletedAt);
}
if (config.enableCreatedBy) {
let createdBy = {
createdBy: {
type: Types.ObjectId,
allowOnCreate: false,
allowOnUpdate: false
}
};
Schema.add(createdBy);
}
if (config.enableUpdatedBy) {
let updatedBy = {
updatedBy: {
type: Types.ObjectId,
allowOnCreate: false,
allowOnUpdate: false
}
};
Schema.add(updatedBy);
}
if (config.enableDeletedBy) {
let deletedBy = {
deletedBy: {
type: Types.ObjectId,
allowOnCreate: false,
allowOnUpdate: false,
}
};
Schema.add(deletedBy);
}
if (config.enableSoftDelete) {
let isDeleted = {
isDeleted: {
type: Types.Boolean,
allowOnCreate: false,
allowOnUpdate: false,
default: false
}
};
Schema.add(isDeleted);
}
if (config.enableDocumentScopes) {
let scope = {
scope: {
rootScope: {
type: [Types.String]
},
readScope: {
type: [Types.String]
},
updateScope: {
type: [Types.String]
},
deleteScope: {
type: [Types.String]
},
associateScope: {
type: [Types.String]
},
type: Types.Object,
allowOnUpdate: false,
allowOnCreate: false
}
};
Schema.add(scope);
}
}
return mongoose.model(Schema.statics.collectionName, Schema);
};
/**
* Add appropriate data to schemas for fields marked as duplicate.
* @param schema
* @param schemas
* @returns {*}
*/
internals.addDuplicateFields = function (schema, schemas) {
let associations = schema.statics.routeOptions.associations;
if (associations) {
for (let key in associations) {
let association = associations[key];
if (association.duplicate && (association.type === 'MANY_ONE' || association.type === 'ONE_ONE')) {
let duplicate = association.duplicate;
if (!_.isArray(duplicate)) {
duplicate = [duplicate];
}
const childSchema = schemas[association.model];
association.duplicate = duplicate = duplicate.map(function(prop) {
//EXPL: Allow for 'duplicate' to be an array of strings
if (_.isString(prop)) {
prop = { field: prop };
}
//EXPL: Set a default name for the duplicated field if no name is specified in "as"
prop.as = prop.as || key + prop.field[0].toUpperCase() + prop.field.slice(1);
return prop;
})
duplicate.forEach(function(prop) {
const field = {};
var fieldName = prop.as;
field[fieldName] = {
type: childSchema.obj[prop.field].type,
allowOnCreate: false,
allowOnUpdate: false
};
schema.add(field);
//EXPL: In the schema of the field being duplicated, keep track of which models/associations are duplicating the field
childSchema.obj[prop.field].duplicated = childSchema.obj[prop.field].duplicated || [];
childSchema.obj[prop.field].duplicated.push({
association: key,
model: schema.statics.collectionName,
as: fieldName
});
})
}
}
}
return schema;
}
/**
* Takes a mongoose schema and extends the fields to include the model associations.
* @param Schema: A mongoose schema.
* @returns {*}: The updated schema.
*/
internals.extendSchemaAssociations = function (Schema, mongoose, modelPath) {
if(Schema.statics.routeOptions){
for (var associationKey in Schema.statics.routeOptions.associations) {
var association = Schema.statics.routeOptions.associations[associationKey];
if (association.type === "MANY_MANY") {
var extendObject = {};
var dataObject = {};
dataObject[association.model] = { type: mongoose.Schema.Types.ObjectId, ref: association.model };
var embedAssociation = association.embedAssociation === undefined ? config.embedAssociations : association.embedAssociation;
//EXPL: if a linking model is defined, add it to the association definition
if (association.linkingModel) {
var linkingModelFiles = require('require-all')(modelPath + '/linking-models');
for (var fileName in linkingModelFiles) {
if (linkingModelFiles[fileName]().modelName === association.linkingModel) {
var linkingModel = linkingModelFiles[fileName]();
break;
}
}
if (!linkingModel) {
throw "unknown linking model: " + association.linkingModel;
}
association.include = {};
let modelExists = true;
try {
association.include.through = mongoose.model(linkingModel.modelName);
}
catch(error) {
modelExists = false;
}
//EXPL: if the association isn't embedded, create separate collection for linking model
if (!embedAssociation) {
const modelName = Schema.statics.collectionName;
if (!modelExists) {
const Types = mongoose.Schema.Types;
linkingModel.Schema[modelName] = {
type: Types.ObjectId,
ref: modelName
};
linkingModel.Schema[association.model] = {
type: Types.ObjectId,
ref: association.model
};
var linkingModelSchema = new mongoose.Schema(linkingModel.Schema, { collection: linkingModel.modelName });
association.include.through = mongoose.model(linkingModel.modelName, linkingModelSchema);
}
//EXPL: we use virtual relationships for linking model collections
Schema.virtual(associationKey, {
ref: linkingModel.modelName,
localField: '_id',
foreignField: modelName
});
}
//EXPL: if the association is embedded, extend original schema with linking model schema
else {
if (!modelExists) {
var linkingModelSchema = new mongoose.Schema(linkingModel.Schema, { collection: linkingModel.modelName });
association.include.through = mongoose.model(linkingModel.modelName, linkingModelSchema);
}
for (var objectKey in linkingModel.Schema) {
var object = linkingModel.Schema[objectKey];
dataObject[objectKey] = object;
}
extendObject[associationKey] = [dataObject];
Schema.add(extendObject);
}
association.include.through.routeOptions = {};
}
else {
//EXPL: if the association isn't embedded and a linking model isn't defined, then we need to create a basic linking collection
if (!embedAssociation) {
const linkingModelName_1 = Schema.statics.collectionName + "_" + association.model;
const linkingModelName_2 = association.model + "_" + Schema.statics.collectionName;
let linkingModelName = linkingModelName_1;
association.include = {};
let modelExists = [true, true];
try {
association.include.through = mongoose.model(linkingModelName_1);
linkingModelName = linkingModelName_1;
}
catch(error) {
modelExists[0] = false;
}
try {
association.include.through = mongoose.model(linkingModelName_2);
linkingModelName = linkingModelName_2;
}
catch(error) {
modelExists[1] = false;
}
const modelName = Schema.statics.collectionName;
if (!modelExists[0] && !modelExists[1]) {
const Types = mongoose.Schema.Types;
linkingModel = { Schema: {} };
linkingModel.Schema[modelName] = {
type: Types.ObjectId,
ref: modelName
};
linkingModel.Schema[association.model] = {
type: Types.ObjectId,
ref: association.model
};
var linkingModelSchema = new mongoose.Schema(linkingModel.Schema, { collection: linkingModelName });
association.include.through = mongoose.model(linkingModelName, linkingModelSchema);
}
association.include.through.routeOptions = {};
//EXPL: we use virtual relationships for linking model collections
Schema.virtual(associationKey, {
ref: linkingModelName,
localField: '_id',
foreignField: modelName
});
}
//EXPL: if the association is embedded, extend the original schema to support the association data
else {
extendObject[associationKey] = [dataObject];
Schema.add(extendObject);
}
}
}
else if (association.type === "ONE_MANY") {//EXPL: for one-many relationships, create a virtual relationship
if (association.foreignField) {
Schema.virtual(associationKey, {
ref: association.model,
localField: '_id',
foreignField: association.foreignField
});
}
}
else if (association.type === "_MANY") {//EXPL: for one sided _many relationships, the association exists as a simple array of objectIds
var extendObject = {};
extendObject[associationKey] = { type: [mongoose.Schema.Types.ObjectId], ref: association.model };
Schema.add(extendObject);
}
else {
//TODO: define ONE_ONE and MANY_ONE associations if needed
}
}
}
return Schema;
};
/**
* Takes a mongoose schema and adds a complete mongoose model to each association in the schema.
* @param Schema: A mongoose schema.
* @param models: The complete list of existing mongoose models.
*/
//TODO: can probably simplify this to a model string/name reference since mongoose models can be accessed globally
internals.associateModels = function (Schema, models) {
if (Schema.statics.routeOptions) {
for (var associationKey in Schema.statics.routeOptions.associations) {
var association = Schema.statics.routeOptions.associations[associationKey];
if (!association.include) {
association.include = {};
}
association.include.model = models[association.model];
association.include.as = associationKey;
}
}
};
module.exports = {
createModel: internals.createModel,
extendSchemaAssociations: internals.extendSchemaAssociations,
associateModels: internals.associateModels,
addDuplicateFields: internals.addDuplicateFields
};