1 | 'use strict';
|
2 |
|
3 | var util = require('./_util');
|
4 |
|
5 | module.exports = function defFunc(ajv) {
|
6 | defFunc.definition = {
|
7 | type: 'object',
|
8 | macro: function (schema) {
|
9 | var schemas = [];
|
10 | for (var pointer in schema)
|
11 | schemas.push(getSchema(pointer, schema[pointer]));
|
12 | return { 'allOf': schemas };
|
13 | },
|
14 | metaSchema: {
|
15 | type: 'object',
|
16 | propertyNames: {
|
17 | type: 'string',
|
18 | format: 'json-pointer'
|
19 | },
|
20 | additionalProperties: util.metaSchemaRef(ajv)
|
21 | }
|
22 | };
|
23 |
|
24 | ajv.addKeyword('deepProperties', defFunc.definition);
|
25 | return ajv;
|
26 | };
|
27 |
|
28 |
|
29 | function getSchema(jsonPointer, schema) {
|
30 | var segments = jsonPointer.split('/');
|
31 | var rootSchema = {};
|
32 | var pointerSchema = rootSchema;
|
33 | for (var i=1; i<segments.length; i++) {
|
34 | var segment = segments[i];
|
35 | var isLast = i == segments.length - 1;
|
36 | segment = unescapeJsonPointer(segment);
|
37 | var properties = pointerSchema.properties = {};
|
38 | var items = undefined;
|
39 | if (/[0-9]+/.test(segment)) {
|
40 | var count = +segment;
|
41 | items = pointerSchema.items = [];
|
42 | while (count--) items.push({});
|
43 | }
|
44 | pointerSchema = isLast ? schema : {};
|
45 | properties[segment] = pointerSchema;
|
46 | if (items) items.push(pointerSchema);
|
47 | }
|
48 | return rootSchema;
|
49 | }
|
50 |
|
51 |
|
52 | function unescapeJsonPointer(str) {
|
53 | return str.replace(/~1/g, '/').replace(/~0/g, '~');
|
54 | }
|