This repository has been archived by the owner on May 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathindex.js
executable file
·128 lines (105 loc) · 2.54 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
'use strict'
const Joi = require('joi');
const externals = {};
externals.build = function (schema) {
// Iterating through the keys of the object
for (let key in schema) {
if (key === "0") {
return schema;
}
if (key === '$array') {
schema = externals.buildJoi(schema[key]);
} else if (schema[key]['$array']) {
schema[key] = externals.buildJoiArray(schema[key]);
} else if (schema[key]['$type']) {
schema[key] = externals.buildJoi(schema[key]);
} else {
schema[key] = externals.build(schema[key]);
}
}
return schema;
};
// Parser for array type of payload
externals.buildJoiArray = (schema) => {
return Joi.array().items(externals.build(schema['$array']));
};
// Parser for types of validation
externals.buildJoi = (schema) => {
// Joi Object
let joiObj = Joi;
switch (schema['$type']) {
case 'string':
joiObj = joiObj.string();
break;
case 'email':
joiObj = joiObj.string().email();
break;
case 'number':
joiObj = joiObj.number();
break;
case 'array':
joiObj = joiObj.array();
break;
case 'object':
joiObj = joiObj.object();
break;
case 'integer':
joiObj = joiObj.number().integer();
break;
case 'boolean':
joiObj = joiObj.boolean();
break;
case 'date':
joiObj = joiObj.date();
break;
case 'timestamp':
if (schema.timestamp) {
joiObj = joiObj.date().timestamp(schema.timestamp);
} else {
joiObj = joiObj.date().timestamp();
}
break;
}
// Min Validation
if (schema.minLength) {
joiObj = joiObj.min(schema.minLength);
}
// Max Validation
if (schema.maxLength) {
joiObj = joiObj.max(schema.maxLength);
}
// Required filed validation
if (schema.required) {
joiObj = joiObj.required();
}
// Regex validation
if (schema.regex) {
joiObj = joiObj.regex(schema.regex);
}
// Option Field
if (schema.optional) {
joiObj = joiObj.optional();
}
// Default field
if (schema.default) {
joiObj = joiObj.default(schema.default);
}
// Min Date Validation
if (schema.minDate) {
if (schema.minDate['$ref']) {
joiObj = joiObj.min(Joi.ref(schema.minDate['$ref']))
} else {
joiObj = joiObj.min(schema.minDate);
}
}
// Max Date Validation
if (schema.maxDate) {
if (schema.maxDate['$ref']) {
joiObj = joiObj.max(Joi.ref(schema.maxDate['$ref']))
} else {
joiObj = joiObj.max(schema.maxDate);
}
}
return joiObj;
};
module.exports = externals;