Skip to content

Commit 4db7e57

Browse files
fix: input schemas mutation (#470)
1 parent e297509 commit 4db7e57

File tree

2 files changed

+72
-3
lines changed

2 files changed

+72
-3
lines changed

index.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,10 @@ function build (schema, options) {
102102
ajvInstance.addSchema(schema, rootSchemaId)
103103

104104
if (options.schema) {
105-
options.schema = clone(options.schema)
105+
const externalSchemas = clone(options.schema)
106106

107-
for (const key of Object.keys(options.schema)) {
108-
const externalSchema = options.schema[key]
107+
for (const key of Object.keys(externalSchemas)) {
108+
const externalSchema = externalSchemas[key]
109109
isValidSchema(externalSchema, key)
110110
extendDateTimeType(externalSchema)
111111

test/ref.test.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
'use strict'
22

3+
const clone = require('rfdc')({ proto: true })
4+
35
const test = require('tap').test
46
const build = require('..')
57

@@ -1822,3 +1824,70 @@ test('ref with same id in properties', (t) => {
18221824
t.equal(output, '{"_id":"foo","image":{"_id":"bar","name":"hello","owner":"baz"}}')
18231825
})
18241826
})
1827+
1828+
test('Should not modify external schemas', (t) => {
1829+
t.plan(2)
1830+
1831+
const externalSchema = {
1832+
uuid: {
1833+
format: 'uuid',
1834+
$id: 'UUID',
1835+
type: 'string'
1836+
},
1837+
Entity: {
1838+
$id: 'Entity',
1839+
type: 'object',
1840+
properties: {
1841+
id: { $ref: 'UUID' },
1842+
id2: { $ref: 'UUID' }
1843+
}
1844+
}
1845+
}
1846+
1847+
const options = { schema: externalSchema }
1848+
const optionsClone = clone(options)
1849+
1850+
const stringify = build({ $ref: 'Entity' }, options)
1851+
1852+
const data = { id: 'a4e4c954-9f5f-443a-aa65-74d95732249a' }
1853+
const output = stringify(data)
1854+
1855+
t.equal(output, JSON.stringify(data))
1856+
t.same(options, optionsClone)
1857+
})
1858+
1859+
test('input schema is not mutated', (t) => {
1860+
t.plan(3)
1861+
1862+
const schema = {
1863+
title: 'object with $ref',
1864+
type: 'object',
1865+
definitions: {
1866+
def: { type: 'string' }
1867+
},
1868+
properties: {
1869+
obj: {
1870+
$ref: '#/definitions/def'
1871+
}
1872+
}
1873+
}
1874+
1875+
const clonedSchema = JSON.parse(JSON.stringify(schema))
1876+
1877+
const object = {
1878+
obj: 'test'
1879+
}
1880+
1881+
const stringify = build(schema)
1882+
const output = stringify(object)
1883+
1884+
try {
1885+
JSON.parse(output)
1886+
t.pass()
1887+
} catch (e) {
1888+
t.fail()
1889+
}
1890+
1891+
t.equal(output, '{"obj":"test"}')
1892+
t.same(schema, clonedSchema)
1893+
})

0 commit comments

Comments
 (0)