-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
75 lines (65 loc) · 1.57 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
module.exports.middleware = middleware;
module.exports.isObject = isObject;
module.exports.isNumber = isNumber;
module.exports.isBoolean = isBoolean;
module.exports.isArray = isArray;
module.exports.parseValue = parseValue;
module.exports.parseObject = parseObject;
module.exports.parseArray = parseArray;
module.exports.parseNumber = parseNumber;
module.exports.parseBoolean = parseBoolean;
function isObject(val) {
return val.constructor === Object;
}
function isNumber(val) {
return !isNaN(parseFloat(val)) && isFinite(val);
}
function isBoolean(val) {
return val === 'false' || val === 'true';
}
function isArray(val) {
return Array.isArray(val);
}
function parseValue(val) {
if (typeof val == 'undefined' || val == '') {
return null;
} else if (isBoolean(val)) {
return parseBoolean(val);
} else if (isArray(val)) {
return parseArray(val);
} else if (isObject(val)) {
return parseObject(val);
} else if (isNumber(val)) {
return parseNumber(val);
} else {
return val;
}
}
function parseObject(obj) {
var result = {};
var key, val;
for (key in obj) {
val = parseValue(obj[key]);
if (val !== null) result[key] = val; // ignore null values
}
return result;
}
function parseArray(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
result[i] = parseValue(arr[i]);
}
return result;
}
function parseNumber(val) {
return Number(val);
}
function parseBoolean(val) {
return val === 'true';
}
function middleware() {
return function(req, res, next) {
req.query = parseObject(req.query);
next();
}
}