UNPKG

1.79 kBJavaScriptView Raw
1/*!
2 * Copyright (c) 2012-2018 Digital Bazaar, Inc. All rights reserved.
3 */
4module.exports = function(types, alternates) {
5 const schema = {
6 title: 'Object Type',
7 description: 'A set of terms, CURIEs, or URLs specifying the type of ' +
8 'the object.',
9 anyOf: []
10 };
11
12 types = Array.isArray(types) ? types : [types];
13
14 // allow single object
15 if(types.length === 1) {
16 schema.anyOf.push({
17 type: 'string',
18 enum: types,
19 errors: {
20 invalid: 'The JSON-LD type information is invalid.',
21 missing: 'The JSON-LD type information is missing.'
22 }
23 });
24 }
25
26 // allow array combination of all types
27 schema.anyOf.push({
28 type: 'array',
29 // minItems: types.length,
30 uniqueItems: true,
31 items: {
32 type: 'string',
33 enum: types
34 },
35 errors: {
36 invalid: 'The JSON-LD type information is invalid.',
37 missing: 'The JSON-LD type information is missing.'
38 }
39 });
40
41 // HACK: madness to support given types *must* exist, while allowing
42 // up to <alternates> other custom types
43 if(alternates !== undefined) {
44 for(let before = 0; before <= alternates; ++before) {
45 const s = {
46 type: 'array',
47 minItems: types.length,
48 uniqueItems: true,
49 items: [],
50 additionalItems: {
51 type: 'string'
52 },
53 errors: {
54 invalid: 'The JSON-LD type information is invalid.',
55 missing: 'The JSON-LD type information is missing.'
56 }
57 };
58 for(let i = 0; i < before; ++i) {
59 s.items.push({type: 'string'});
60 }
61 for(let i = 0; i < types.length; ++i) {
62 s.items.push({
63 type: 'string',
64 enum: types
65 });
66 }
67 schema.anyOf.push(s);
68 }
69 }
70
71 return schema;
72};