Skip to content

Commit 335ded3

Browse files
authored
fix side effect on items $ref (#302)
1 parent 225cf50 commit 335ded3

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

index.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -957,7 +957,7 @@ function buildObject (location, code, name) {
957957
}
958958

959959
function buildArray (location, code, name, key = null) {
960-
const schema = location.schema
960+
let schema = location.schema
961961
code += `
962962
function ${name} (obj) {
963963
`
@@ -979,6 +979,10 @@ function buildArray (location, code, name, key = null) {
979979
}
980980

981981
if (schema.items.$ref) {
982+
if (!schema[fjsCloned]) {
983+
schema = clone(location.schema)
984+
schema[fjsCloned] = true
985+
}
982986
location = refFinder(schema.items.$ref, location)
983987
schema.items = location.schema
984988
}
@@ -1215,7 +1219,7 @@ function nested (laterCode, name, key, location, subKey, isArray) {
12151219
`
12161220
} else if ('const' in schema) {
12171221
code += `
1218-
if(ajv.validate(${require('util').inspect(schema, { depth: null, showHidden: false })}, obj${accessor}))
1222+
if(ajv.validate(${JSON.stringify(schema)}, obj${accessor}))
12191223
json += '${JSON.stringify(schema.const)}'
12201224
else
12211225
throw new Error(\`Item $\{JSON.stringify(obj${accessor})} does not match schema definition.\`)

test/side-effect.test.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,37 @@ test('multiple $ref tree', t => {
121121
t.is(value, '{"people":{"name":"hello","age":42}}')
122122
t.deepEqual(schema, clonedSchema)
123123
})
124+
125+
test('must not mutate items $ref', t => {
126+
t.plan(2)
127+
128+
const referenceSchema = {
129+
$id: 'ShowSchema',
130+
$schema: 'http://json-schema.org/draft-07/schema#',
131+
type: 'object',
132+
properties: {
133+
name: {
134+
type: 'string'
135+
}
136+
}
137+
}
138+
139+
const schema = {
140+
$id: 'ListSchema',
141+
$schema: 'http://json-schema.org/draft-07/schema#',
142+
type: 'array',
143+
items: {
144+
$ref: 'ShowSchema#'
145+
}
146+
}
147+
const clonedSchema = clone(schema)
148+
const stringify = build(schema, {
149+
schema: {
150+
[referenceSchema.$id]: referenceSchema
151+
}
152+
})
153+
154+
const value = stringify([{ name: 'foo' }])
155+
t.is(value, '[{"name":"foo"}]')
156+
t.deepEqual(schema, clonedSchema)
157+
})

0 commit comments

Comments
 (0)