-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
182 lines (148 loc) · 4.33 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
'use strict';
const Joi = require('joi');
const debug = require('debug')('eJoi');
exports = module.exports = eJoi;
exports.callback = validateCallback;
exports.promiseLike = polyfillPromiseLike;
/**
* Default options for validateCallback
*
* @type {Object}
* @property {boolean} useNextRoute Pass control to the next route. (Only if the validation is successful)
* @property {boolean|string|Array} override Specify the target property to override according to type
*/
const defaults = {
nextRoute: false,
override: true,
};
/**
* Validation middleware using Joi
*
* @public
* @param {Object|Object[]} schema Joi type object or plain object
* @param {Object} [options={}] Joi validate options
* @param {Function} [callback=validateCallback()] validation callback
* @returns {Function} middleware
*/
function eJoi(schema, options = {}, callback = validateCallback()) {
const compiled = compile(schema);
const props = getPropsByChildren(compiled);
if (!props.length) {
throw new Error('There are no properties to compare.');
}
// eJoi(schema, callback)
if (typeof options === 'function') {
callback = options;
options = {};
}
return function eJoi(req, res, next) {
const stripUnknownRequest = stripUnknownProperties(req, props);
debug('Joi.validate() <= %O', stripUnknownRequest);
const result = Joi.validate(stripUnknownRequest, compiled, options);
debug('Joi.validate() => %O', result);
callback(req, res, next, result);
};
}
/**
* It is a callback that performs validation
*
* @public
* @param {Object} [options={}] options for handling callback
* @returns {Function} validation callback
*/
function validateCallback(options = {}) {
const opts = Object.assign({}, defaults, options);
return (req, res, next, promise) => {
// Polyfill extension for promise-like
polyfillPromiseLike(promise);
promise
.then(value => {
if (opts.override) {
Object.assign(req, stripUnknownProperties(value, opts.override));
}
if (opts.nextRoute) {
return next('route');
}
next();
})
.catch(error => next(error));
};
}
/**
* Polyfill extension method for promise-like
*
* @public
* @param {Object} result Joi validate result
* @returns {Object} Apply polyfill if promise-like is not supported
*/
function polyfillPromiseLike(result) {
// return if promise-like support
if (typeof result.then === 'function') {
return result;
}
debug('This schema is a version that does not support Promise-like.');
const { error, value } = result;
result.then = (resolve, reject) => {
if (error) { return Promise.reject(error).catch(reject); }
return Promise.resolve(value).then(resolve);
};
result.catch = (reject) => {
if (error) { return Promise.reject(error).catch(reject); }
return Promise.resolve(value);
};
return result;
}
/**
* Joi compile
*
* @private
* @param {Object} schema Joi type object or plain object
* @returns {Object} Joi schema object
*/
function compile(schema) {
if (typeof schema !== 'object') {
throw new Error('Invalid schema object');
}
try {
return schema.isJoi ? schema : Joi.compile(schema);
} catch (err) {
throw err;
}
}
/**
* Extract the object properties
*
* @private
* @param {Object} source source object
* @param {boolean|string|Array} props object properties
* @returns {Object} extract reference object
*/
function stripUnknownProperties(source, props) {
const extractObject = {};
// stripUnknownProperties({}, false);
if (!props) { return extractObject; }
// No strip processing
// stripUnknownProperties({}, true);
if (props === true) { return source; }
// stripUnknownProperties({}, 'propName');
if (typeof props === 'string') {
props = [props];
}
return props.reduce((obj, prop) => {
obj[prop] = source[prop];
return obj;
}, extractObject);
}
/**
* Extracts the target attributes of the request object to be compared from the schema
*
* @private
* @param {Object} schema Joi schema object
* @returns {Array} children keys
*/
function getPropsByChildren(schema) {
const describe = schema.describe();
// extract only for object type
const getKeys = obj => obj.type === 'object' ? Object.keys(obj.children) : [];
return describe.type === 'alternatives' ? getKeys(describe.base) : getKeys(describe);
}