Skip to content

Commit db2fa85

Browse files
ruiaraujodelvedor
authored andcommitted
Allow empty schemas as properties. (#105)
It allows covering opaque types. I am using this together with a GraphQL endpoint which has custom scalars. These scalars are opaque from the type system so a JSON schema cannot be derived.
1 parent c2751cf commit db2fa85

File tree

2 files changed

+93
-1
lines changed

2 files changed

+93
-1
lines changed

index.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,13 @@ function nested (laterCode, name, key, schema, externalSchema, fullSchema, subKe
726726
code += `
727727
else json+= null
728728
`
729-
} else throw new Error(`${schema} unsupported`)
729+
} else if (isEmpty(schema)) {
730+
code += `
731+
json += JSON.stringify(obj${accessor})
732+
`
733+
} else {
734+
throw new Error(`${schema} unsupported`)
735+
}
730736
break
731737
default:
732738
if (Array.isArray(type)) {
@@ -814,4 +820,11 @@ function isValidSchema (schema, externalSchema) {
814820
ajv.removeSchema()
815821
}
816822

823+
function isEmpty (schema) {
824+
for (var key in schema) {
825+
if (schema.hasOwnProperty(key)) return false
826+
}
827+
return true
828+
}
829+
817830
module.exports = build

test/any.test.js

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
'use strict'
2+
3+
const test = require('tap').test
4+
const build = require('..')
5+
6+
test('object with nested random property', (t) => {
7+
t.plan(4)
8+
9+
const schema = {
10+
title: 'empty schema to allow any object',
11+
type: 'object',
12+
properties: {
13+
id: {
14+
type: 'number'
15+
},
16+
name: {}
17+
}
18+
}
19+
const stringify = build(schema)
20+
21+
try {
22+
const value = stringify({
23+
id: 1,
24+
name: 'string'
25+
})
26+
t.is(value, '{"id":1,"name":"string"}')
27+
} catch (e) {
28+
t.fail()
29+
}
30+
try {
31+
const value = stringify({
32+
id: 1,
33+
name: {
34+
first: 'name',
35+
last: 'last'
36+
}
37+
})
38+
t.is(value, '{"id":1,"name":{"first":"name","last":"last"}}')
39+
} catch (e) {
40+
t.fail()
41+
}
42+
try {
43+
const value = stringify({
44+
id: 1,
45+
name: null
46+
})
47+
t.is(value, '{"id":1,"name":null}')
48+
} catch (e) {
49+
t.fail()
50+
}
51+
try {
52+
const value = stringify({
53+
id: 1,
54+
name: ['first', 'last']
55+
})
56+
t.is(value, '{"id":1,"name":["first","last"]}')
57+
} catch (e) {
58+
t.fail()
59+
}
60+
})
61+
62+
test('array with random items', (t) => {
63+
t.plan(1)
64+
65+
const schema = {
66+
title: 'empty schema to allow any object',
67+
type: 'array',
68+
items: {
69+
}
70+
}
71+
const stringify = build(schema)
72+
73+
try {
74+
const value = stringify([1, 'string', null])
75+
t.is(value, '[1,"string",null]')
76+
} catch (e) {
77+
t.fail()
78+
}
79+
})

0 commit comments

Comments
 (0)