forked from tlivings/enjoi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (41 loc) · 1.78 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
const Joi = require('joi');
const Hoek = require('hoek');
const Util = require('util');
const SchemaResolver = require('./lib/resolver');
const schemaSchema = Joi.alternatives(Joi.object().unknown(true), Joi.string()).required();
const optionsSchema = Joi.object({
subSchemas: Joi.object().unknown(true).allow(null),
types: Joi.object().unknown(true).allow(null),
extensions: Joi.array().items(Joi.object().unknown(true)).allow(null),
refineType: Joi.func().allow(null),
strictMode: Joi.boolean().default(false),
});
const validate = function (schema, options = {}) {
const validateOptions = Joi.validate(options, optionsSchema);
Hoek.assert(!validateOptions.error, validateOptions.error);
const validateSchema = Joi.validate(schema, schemaSchema);
Hoek.assert(!validateSchema.error, validateSchema.error);
return validateOptions.value;
};
exports.defaults = function (defaults = {}) {
return {
schema(schema, options = {}) {
const merged = {
subSchemas: Object.assign({}, defaults.subSchemas, options.subSchemas),
types: Object.assign({}, defaults.types, options.types),
extensions: defaults.extensions || [],
refineType: options.refineType || defaults.refineType,
strictMode: options.strictMode || defaults.strictMode
};
if (Util.isArray(options.extensions)) {
merged.extensions = merged.extensions.concat(options.extensions);
}
options = validate(schema, merged);
return new SchemaResolver(schema, options).resolve();
}
};
};
exports.schema = function (schema, options = {}) {
options = validate(schema, options);
return new SchemaResolver(schema, options).resolve();
};