-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathmongoose.js
322 lines (275 loc) · 8.86 KB
/
mongoose.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
const _ = require('lodash');
const Interface = require('forest-express');
const utils = require('../utils/schema');
/* eslint-disable */
function unflatten(data) {
const result = {};
for (var key in data) {
var keys = key.split('.');
keys.reduce((result, subKey, index) => {
if (!result[subKey]) {
if (Number.isNaN(Number(keys[index + 1]))) {
result[subKey] = keys.length - 1 === index ? data[key] : {};
} else {
result[subKey] = [];
}
}
return result[subKey];
}, result);
}
return result;
}
/* eslint-enable */
module.exports = async (model, opts) => {
const fields = [];
const paths = unflatten(model.schema.paths);
const { Mongoose } = opts;
// NOTICE: mongoose.base is used when opts.mongoose is not the default connection.
let schemaType;
function formatRef(ref) {
const referenceModel = utils.getReferenceModel(opts, ref);
if (referenceModel) {
return utils.getModelName(referenceModel);
}
Interface.logger.warn(`Cannot find the reference "${ref}" on the model "${model.modelName}".`);
return null;
}
function detectReference(fieldInfo) {
if (fieldInfo.options) {
if (fieldInfo.options.ref && fieldInfo.options.type) {
return `${formatRef(fieldInfo.options.ref)}._id`;
}
if (_.isArray(fieldInfo.options.type) && fieldInfo.options.type.length
&& fieldInfo.options.type[0].ref && fieldInfo.options.type[0].type) {
return `${formatRef(fieldInfo.options.type[0].ref)}._id`;
}
}
return null;
}
function objectType(fieldsInfo, getType) {
const type = { fields: [] };
Object.keys(fieldsInfo).forEach((fieldName) => {
const fieldInfo = fieldsInfo[fieldName];
const field = {
field: fieldName,
type: getType(fieldName),
};
if (fieldName === '_id') {
field.isPrimaryKey = true;
}
if (!field.type) { return; }
const ref = detectReference(fieldInfo);
if (ref) { field.reference = ref; }
if (fieldInfo.enumValues && fieldInfo.enumValues.length) {
field.enums = fieldInfo.enumValues;
}
if (fieldInfo.enum
&& Array.isArray(fieldInfo.enum)
&& fieldInfo.enum.length) {
field.enums = fieldInfo.enum;
}
type.fields.push(field);
});
return type;
}
function getTypeFromNative(type) {
if (type instanceof Array) {
if (_.isEmpty(type)) {
return [null];
}
return [getTypeFromNative(type[0].type || type[0])];
}
if (_.isPlainObject(type)) {
if (_.isEmpty(type)) { return 'Json'; }
if (type.type) {
if (type.enum) {
// NOTICE: Detect enum values for Enums in subdocument arrays.
return 'Enum';
}
return getTypeFromNative(type.type);
}
return objectType(type, (key) => getTypeFromNative(type[key]));
}
if (_.isFunction(type) && type.name === 'ObjectId') {
return 'String';
}
if (type instanceof Mongoose.Schema) {
return schemaType(type);
}
switch (type) {
case String:
return 'String';
case Boolean:
return 'Boolean';
case Number:
return 'Number';
case Date:
return 'Date';
default:
return null;
}
}
function getTypeFromMongoose(fieldInfo) {
if (_.isPlainObject(fieldInfo) && !fieldInfo.path) {
// Deal with Object
return objectType(fieldInfo, (fieldName) => getTypeFromMongoose(fieldInfo[fieldName]));
}
if (fieldInfo.instance === 'Array') {
if (_.isEmpty(fieldInfo.options.type) && !_.isUndefined(fieldInfo.options.type)) {
return 'Json';
}
// Deal with Array
if (fieldInfo.caster.instance && (fieldInfo.caster.options.ref
|| _.keys(fieldInfo.caster.options).length === 0)) {
return [getTypeFromMongoose(fieldInfo.caster)];
}
if (fieldInfo.options.type[0] instanceof Mongoose.Schema) {
// Schema
return [schemaType(fieldInfo.options.type[0])];
}
// NOTICE: Object with `type` reserved keyword.
// See: https://mongoosejs.com/docs/schematypes.html#type-key
if (fieldInfo.options.type[0] instanceof Object
&& fieldInfo.options.type[0].type
// NOTICE: Bypass for schemas like `[{ type: {type: String}, ... }]` where "type" is used
// as property, and thus we are in the case of an array of embedded documents.
// See: https://mongoosejs.com/docs/faq.html#type-key
&& !fieldInfo.options.type[0].type.type) {
return [getTypeFromNative(fieldInfo.options.type[0])];
}
// Object
return [objectType(fieldInfo.options.type[0], (key) =>
getTypeFromNative(fieldInfo.options.type[0][key]))];
}
if (fieldInfo.enumValues && fieldInfo.enumValues.length) {
return 'Enum';
}
if (fieldInfo.instance === 'ObjectID') {
// Deal with ObjectID
return 'String';
}
if (fieldInfo.instance === 'Embedded') {
return objectType(fieldInfo.schema.obj, (fieldName) =>
getTypeFromNative(fieldInfo.schema.obj[fieldName]));
}
if (fieldInfo.instance === 'Mixed') {
// Deal with Mixed object
// NOTICE: Object and {} are detected as Json type as they don't have schema.
if (_.isEmpty(fieldInfo.options.type) && !_.isUndefined(fieldInfo.options.type)) {
return 'Json';
}
if (_.isEmpty(fieldInfo.options) && !_.isUndefined(fieldInfo.options)) {
return 'Json';
}
return null;
}
// Deal with primitive type
return fieldInfo.instance
|| (fieldInfo.options && getTypeFromNative(fieldInfo.options.type))
|| null;
}
schemaType = (type) => ({
fields: _.map(type.paths, (fieldType, fieldName) => {
const field = {
field: fieldName,
type: getTypeFromMongoose(fieldType),
};
if (fieldName === '_id') {
field.isPrimaryKey = true;
}
if (fieldType.enumValues && fieldType.enumValues.length) {
field.enums = fieldType.enumValues;
}
return field;
}),
});
function getRequired(fieldInfo) {
return fieldInfo.isRequired === true
|| (
fieldInfo.path === '_id'
&& !fieldInfo.options.auto
&& fieldInfo.options.type !== Mongoose.ObjectId
);
}
function getValidations(fieldInfo) {
const validations = [];
if (fieldInfo.validators && fieldInfo.validators.length > 0) {
_.each(fieldInfo.validators, (validator) => {
if (validator.type === 'required') {
validations.push({
type: 'is present',
});
}
if (validator.type === 'minlength') {
validations.push({
type: 'is longer than',
value: validator.minlength,
});
}
if (validator.type === 'maxlength') {
validations.push({
type: 'is shorter than',
value: validator.maxlength,
});
}
if (validator.type === 'min') {
validations.push({
type: 'is greater than',
value: validator.min,
});
}
if (validator.type === 'max') {
validations.push({
type: 'is less than',
value: validator.max,
});
}
});
}
return validations;
}
function getFieldSchema(path) {
const fieldInfo = paths[path];
const schema = { field: path, type: getTypeFromMongoose(fieldInfo) };
const ref = detectReference(fieldInfo);
if (ref) { schema.reference = ref; }
if (fieldInfo.enumValues && fieldInfo.enumValues.length) {
schema.enums = fieldInfo.enumValues;
}
// NOTICE: Create enums from caster (for ['Enum'] type).
if (fieldInfo.caster && fieldInfo.caster.enumValues && fieldInfo.caster.enumValues.length) {
schema.enums = fieldInfo.caster.enumValues;
}
const isRequired = getRequired(fieldInfo);
if (isRequired) {
schema.isRequired = isRequired;
}
if (path === '_id') {
schema.isPrimaryKey = true;
}
if (fieldInfo.options && !_.isNull(fieldInfo.options.default)
&& !_.isUndefined(fieldInfo.options.default)
&& !_.isFunction(fieldInfo.options.default)) {
schema.defaultValue = fieldInfo.options.default;
}
schema.validations = getValidations(fieldInfo);
if (schema.validations.length === 0) {
delete schema.validations;
}
return schema;
}
Object.keys(paths).forEach(async (path) => {
if (path === '__v') { return; }
const field = getFieldSchema(path);
fields.push(field);
});
return {
name: utils.getModelName(model),
// TODO: Remove nameOld attribute once the lianas versions older than 2.0.0 are minority.
nameOld: model.collection.name.replace(' ', ''),
idField: '_id',
primaryKeys: ['_id'],
isCompositePrimary: false,
fields,
};
};