For my daily work I need an additional custom “AnyOf” validator for Schema-Inspector. Schema-Inspector is a powerful tool to sanitize and validate JS objects. So I started my first draft as follows, in ES6. I want to export an any-of module like this:

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
import SchemaInspector from 'schema-inspector';
 
// The value of this keyword MUST be an array. This array MUST have at least one element.
// Each element of this array MUST be an object, and each object MUST be a valid JSON Schema.
 
const resultGenerator = function* (schemas, candidates) {
 
    //destructure in for-of loop to get the indices of the candidates
    for (let [key, candidate] of candidates.entries()) {
 
        let initResult = {index: key};
        let result = {};
        for (let schema of schemas['$anyOf']) {
 
            let r = SchemaInspector.validate(schema, candidate);
            result = Object.assign(initResult, r);
            if (r.valid) break;
        }
 
        yield result;
    }
 
};
 
export default function (schemas, candidates) {
 
    if (!(candidates instanceof Array) || candidates.length == 0) {
        this.report('candidates must be an array with at least one element');
        return false;
    }
 
    for (let result of resultGenerator(schemas, candidates)) {
        if (!result.valid) {
            this.report('candidate ' + result.index + ' ' + result.format());
            return false;
        }
    }
 
};

So and here is my testfile:

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
import SchemaInspector from 'schema-inspector';
import anyOf from './any-of';
 
const SubSchema1 = {
    type: 'object',
    properties: {
        customSchemaObject1: {
            type: 'string'
        }
    }
};
 
const SubSchema2 = {
    type: 'object',
    properties: {
        customSchemaObject2: {
            type: 'string'
        }
    }
};
 
const SampleSchema = {
    type: 'object',
    properties: {
        name: {
            type: 'string'
        },
        items: {
            type: 'array',
            $anyOf: [SubSchema1, SubSchema2],
            exec: anyOf
        }
    }
};
 
const sampleData = {
    name: 'MyObject',
    items: [
        {
            customSchemaObject1: 'Just testing'
        },
        {
            customSchemaObject2: 'Just another test'
        }
    ]
};
 
const result = SchemaInspector.validate(SampleSchema, sampleData);
console.log(result);

npm package:

https://www.npmjs.com/package/schema-inspector-anyOf