-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
111 lines (93 loc) · 2.76 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
const Ajv = require('ajv')
// Super types
Ajv.prototype.superTypes = {
date: { format: 'date'},
time: { format: 'time'},
'date-time': { format: 'date-time'},
uri: { format: 'uri'},
url: { format: 'uri'},
email: { format: 'email' },
hostname: { format: 'hostname'},
ip: { format: 'ipv4'},
ipv4: { format: 'ipv4'},
ipv6: { format: 'ipv6'},
regex: { format: 'regex'},
uuid: { format: 'uuid'},
'json-pointer': { format: 'json-pointer'},
'relative-json-pointer': {
format: 'relative-json-pointer' },
}
// Add a super type to AJV
Ajv.prototype.addType = function (name, opt) {
// Add the super type keyword to AJV
this.addKeyword('type_' + name, opt)
// Register type to convert to correct key name for AJV
this.superTypes[name] = {}
this.superTypes[name]['type_' + name] = true
// Return this to pipe functions
return this
}
// TODO hierarchy search
Ajv.prototype.processProps = function (schema) {
const props = schema.properties
// Create required array property
if (!schema.required) {
schema.required = []
}
// Search for super type entries
for (let key of Object.keys(props)) {
// Convert string settings into object
if (typeof props[key] === 'string') {
props[key] = {
type: props[key]
}
}
// Check if the property is a super type
if (this.superTypes[props[key].type]) {
// Extends the prop attributes
Object.assign(
props[key],
this.superTypes[props[key].type])
delete props[key].type
}
// Check super required property
if (props[key].required && props[key].required === true) {
if (!schema.required.includes(key)) {
schema.required.push(key)
}
delete props[key].required
}
// Setup own properties
if (props[key].properties) {
props[key] = this.getSuperSchema(props[key])
}
// Check if the property is a super required
if (key.charAt(0) === '*') {
const _key = key.substring(1)
if (!schema.required.includes(_key)) {
schema.required.push(_key)
}
props[_key] = props[key]
delete props[key]
}
}
return schema
}
Ajv.prototype.getSuperSchema = function(schema) {
if (typeof schema !== 'object') {
return schema
}
// Too bad for cloning objects... =/
const resSchema = JSON.parse(JSON.stringify(schema))
if(resSchema.type === "array")
resSchema.items = this.processProps(resSchema.items);
else resSchema = this.processProps(resSchema);
return resSchema;
}
// Save default validate functions to convert super types
Ajv.prototype._super_validate = Ajv.prototype.validate
// Redefine validate functions
Ajv.prototype.validate = function (schema, data) {
return this._super_validate(this.getSuperSchema(schema), data)
}
module.exports = Ajv