-
Notifications
You must be signed in to change notification settings - Fork 1
/
ajv.js
91 lines (85 loc) · 2.07 KB
/
ajv.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
'use strict';
const { v5: uuidv5 } = require('uuid');
const DEFAULT_SCHEMA_ID = 'http://json-schema.org/schema';
function dynamic(ajv) {
ajv.addKeyword('dynamic', {
macro,
metaSchema: ajv.getSchema(DEFAULT_SCHEMA_ID).schema
});
return ajv;
}
function macro(schema, parentSchema, context) {
const ajv = context.self;
const $ref = '/' + uuidv5(JSON.stringify(schema), uuidv5.URL);
if (!ajv.getSchema($ref)) {
ajv.addSchema(createSchema(schema, $ref), $ref);
}
return { $ref };
}
function createSchema(schema, $ref) {
const stringAndRef = {
type: 'array',
minItems: 2,
maxItems: 2,
items: [ { type: 'string' }, { $ref } ]
};
const anyAndRef = {
type: 'array',
minItems: 2,
maxItems: 2,
items: [ {}, { $ref } ]
};
const template = {
allOf: stringAndRef.items
};
const properties = {
$param: {
oneOf: [
{ type: 'string' },
stringAndRef
]
},
$template: {
oneOf: [
template,
{ type: 'array', items: template }
]
},
$guard: {
type: 'array',
items: stringAndRef
},
$switch: {
type: 'array',
minItems: 2,
maxItems: 2,
items: [
{ type: 'string' },
{ type: 'array', items: anyAndRef }
]
},
$function: {
type: 'string'
}
};
const requiredKeys = Object.keys(properties).map((key) => {
return { required: [ key ] };
});
return {
oneOf: [
{
allOf: [
schema,
{ not: { type: 'object', anyOf: requiredKeys } }
]
},
{
type: 'object',
additionalProperties: false,
properties,
oneOf: requiredKeys
}
]
};
}
module.exports = dynamic;