-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
329 lines (269 loc) · 8.9 KB
/
index.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
const Assert = require("assert");
const Hoek = require("@hapi/hoek");
const Joi = require("joi");
const internals = {
mongoose: null,
joiGlobalOptions: {},
};
internals.root = (mongoose, options, subdocumentOptions) => {
Assert(mongoose);
internals.mongoose = mongoose;
internals.joiGlobalOptions = options || null;
internals.subdocumentOptions = subdocumentOptions || null;
return {
convert: internals.convert,
mongooseValidateWrapper: internals.mongooseValidateWrapper,
};
};
internals.convert = (joiObject, options = {}) => {
const typeKey = options.typeKey || "type";
if (joiObject === undefined) {
throw new Error("Ensure the value you're trying to convert exists!");
}
if (!Joi.isSchema(joiObject)) {
joiObject = Joi.object(joiObject);
}
const output = {};
if (joiObject._flags.default !== undefined) {
output.default = joiObject._flags.default;
}
if (joiObject.$_terms.metas.length > 0) {
const toClass = {}.toString;
// console.log(JSON.stringify(joiObject, null, ' '));
// Iterate through the array
for (const meta of joiObject.$_terms.metas) {
// Only add objects
if (toClass.call(meta) !== "[object Object]") {
continue;
}
if (meta._mongoose) {
for (const [key, value] of Object.entries(meta._mongoose)) {
// Check for _objectId
if (key === "type" && value === "ObjectId") {
output[typeKey] = internals.mongoose.Schema.Types.ObjectId;
const originalJoiObject = Hoek.clone(joiObject);
// joiObject = Joi.alternatives([
// joiObject,
// Joi.object().type(internals.mongoose.Schema.Types.ObjectId)
// ]);
joiObject._isObjectId = true;
originalJoiObject._isObjectId = true;
joiObject.$_terms.metas = originalJoiObject.$_terms.metas;
joiObject._flags = originalJoiObject._flags;
output.validate = internals.mongooseValidateWrapper.bind(
this,
originalJoiObject
);
} else {
output[key] = value;
}
}
}
}
}
if (joiObject.type === "object") {
// Allow for empty object - https://github.com/hapijs/joi/blob/v9.0.0-3/API.md#object
// And unknown keys
if (!joiObject.$_terms.keys || joiObject._flags.unknown)
return { [typeKey]: internals.mongoose.Schema.Types.Mixed };
joiObject.$_terms.keys.forEach((child) => {
output[child.key] = internals.convert(child.schema, options);
if (internals.isObjectId(child.schema)) {
child.schema._isObjectId = true;
// child.schema = Joi.alternatives([
// Hoek.clone(child.schema),
// Joi.object().type(internals.mongoose.Types.ObjectId)
// ]);
}
});
return output;
}
output.validate = {
validator: internals.mongooseValidateWrapper.bind(this, joiObject),
};
// We don't want the required key added onto objects, hence why its here.
// If it's added onto objects, Mongoose complains because it can't
// understand the type 'true'. #truestory #lol
if (joiObject._flags.presence === "required") {
output.required = true;
}
if (output[typeKey]) {
return output;
}
output[typeKey] = internals.typeDeterminer(joiObject, options);
// If this is an array, let's get rid of the validation cos it causes major
// beef with validation
if (Array.isArray(output[typeKey])) {
delete output.validate;
}
return output;
};
internals.typeDeterminer = (joiObject, options = {}) => {
if (joiObject.type === "string") {
// If the type has already been set, that's probably
// because it was an ObjectId. In this case, don't set the
// type as a string.
return String;
}
if (joiObject.type === "number") {
return Number;
}
if (joiObject.type === "date") {
return Date;
}
if (joiObject.type === "boolean") {
return Boolean;
}
let types = {};
const type = [];
if (joiObject.type === "array") {
// Go through each of the children in the array and get their types
for (const meta of joiObject.$_terms.items) {
if (types[meta.type]) {
types[meta.type]++;
} else {
types[meta.type] = 1;
}
}
// If there are multiple types, there's not much else we can do as far as Mongoose goes...
if (Object.keys(types).length > 1) {
type.push(internals.mongoose.Schema.Types.Mixed);
return type;
}
// If there are multiple of the same type, this means that there are different schemas.
// This is alright cos we know they're all the same type
const [firstKey] = Object.keys(types);
if (types[firstKey] > 1) {
type.push(internals.typeDeterminer({ type: firstKey }));
return type;
}
if (joiObject.$_terms.items.length === 0) {
return type;
}
// Collate all meta objects because these need to be pushed into the schema options
let schemaOptions = joiObject.$_terms.metas.reduce(
(opts, currentOption) => ({
...opts._mongoose,
...currentOption._mongoose,
}),
{}
);
// Combine the explicit schema options with the global subdocument options
if (internals.subdocumentOptions) {
schemaOptions = {
...internals.subdocumentOptions,
...schemaOptions,
};
}
if (
internals.typeDeterminer(joiObject.$_terms.items[0], options) !== Object
) {
type.push(internals.convert(joiObject.$_terms.items[0], options));
} else {
type.push(
new internals.mongoose.Schema(
internals.convert(joiObject.$_terms.items[0], options),
schemaOptions
)
);
}
return type;
}
if (joiObject.type === "alternatives") {
types = {};
if (joiObject.$_terms.matches.length === 0) {
return internals.mongoose.Schema.Types.Mixed;
}
// Go through each of the children in the array and get their types
for (const match of joiObject.$_terms.matches) {
types[match.schema.type] = types[match.schema.type]
? types[match.schema.type] + 1
: (types[match.schema.type] = 1);
}
// If there are multiple types, there's not much else we can do as far as Mongoose goes...
if (Object.keys(types).length > 1) {
return internals.mongoose.Schema.Types.Mixed;
}
// If there are multiple of the same type, this means that there are different schemas, but the same type :D
const [firstKey] = Object.keys(types);
if (types[firstKey] > 1) {
return internals.typeDeterminer({ type: firstKey });
}
// If we're here, it's because there's a single type, and one schema. So actually, an alternative didn't need to be used...
return internals.typeDeterminer(joiObject.$_terms.matches[0].schema);
// // If there are multiple types in the items, set the type to mixed
// mixedTypeFound = false;
// if (joiObject.$_terms.matches.length === 0) {
// mixedTypeFound = true;
// }
// types = {};
// joiObject.$_terms.matches.forEach(function (item) {
// types[item.schema.type] = true;
// });
// // If we have one type, then all array items are this
// if (Object.keys(types).length === 1) {
// output = internals.convert(joiObject.$_terms.matches[0].schema);
// } else {
// mixedTypeFound = true;
// }
// if (mixedTypeFound) {
// return internals.mongoose.Schema.Types.Mixed;
// }
// return output;
}
if (joiObject.type === "object") {
return Object;
}
if (joiObject.type === "any") {
return internals.mongoose.Schema.Types.Mixed;
}
throw new TypeError(
'Unsupported Joi type: "' +
joiObject.type +
"\"! Raise an issue on GitHub if you'd like it to be added!"
);
};
internals.isObjectId = (joiObject) => {
if (joiObject.$_terms.metas.length > 0) {
const toClass = {}.toString;
for (const meta of joiObject.$_terms.metas) {
// Only add objects
if (toClass.call(meta) !== "[object Object]") {
continue;
}
if (meta._mongoose) {
for (const key in meta._mongoose) {
// Check for _objectId
if (key === "type" && meta._mongoose[key] === "ObjectId") {
return true;
} else {
return false;
}
}
}
}
}
return false;
};
internals.mongooseValidateWrapper = async (originalJoiSchema, value) => {
let joiSchema = Hoek.clone(originalJoiSchema);
if (joiSchema._isObjectId) {
joiSchema = Joi.alternatives(
joiSchema,
Joi.object().instance(internals.mongoose.Types.ObjectId)
);
}
try {
const { error } = joiSchema.validate(value, internals.joiGlobalOptions);
if (error) return false;
return true;
} catch (err) {
try {
await joiSchema.validateAsync(value, internals.joiGlobalOptions);
return true;
} catch (err) {
return false;
}
}
};
module.exports = internals.root;