check-params.js
1.41 KB
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
const _ = require('lodash');
const getType = (fn) => {
const match = fn && fn.toString().match(/^\s*function (\w+)/);
return match ? match[1] : '';
};
const simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/;
const assetType = (value, type) => {
const expectedType = getType(type);
let valid;
if (simpleCheckRE.test(expectedType)) {
const t = typeof value;
valid = t === expectedType.toLowerCase();
// for primitive wrapper objects
if (!valid && t === 'object') {
valid = value instanceof type;
}
} else if (expectedType === 'Object') {
valid = value.toString() === '[object Object]';
} else if (expectedType === 'Array') {
valid = Array.isArray(value);
} else {
valid = value instanceof type;
}
return valid;
};
const getParams = (params, apiInfo) => {
let props = {};
if (apiInfo.params) {
_.each(apiInfo.params, (v, k) => {
const paramItem = params[k];
if (!paramItem) {
if (v.require) {
throw Error(`${k} params is not undefined`);
}
return;
}
if (!assetType(paramItem, v.type)) {
throw Error(`${k} params is not ${getType(v.type)}`);
}
props[k] = paramItem;
});
}
return params;
};
module.exports = {
getParams
};