Skip to content

Commit b117761

Browse files
Eommmcollina
authored andcommitted
Fix relative ref (#185)
* add test case * fix resolve ref scope
1 parent e2b5d35 commit b117761

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -533,7 +533,9 @@ function sanitizeKey (key) {
533533
function buildCode (schema, code, laterCode, name, externalSchema, fullSchema) {
534534
Object.keys(schema.properties || {}).forEach((key, i, a) => {
535535
if (schema.properties[key].$ref) {
536-
schema.properties[key] = refFinder(schema.properties[key].$ref, fullSchema, externalSchema)
536+
// if the schema object is deep in the tree, we must resolve the ref in the parent scope
537+
const isRelative = schema.definitions && schema.properties[key].$ref[0] === '#'
538+
schema.properties[key] = refFinder(schema.properties[key].$ref, isRelative ? schema : fullSchema, externalSchema)
537539
}
538540

539541
// Using obj['key'] !== undefined instead of obj.hasOwnProperty(prop) for perf reasons,

test/ref.test.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -766,3 +766,41 @@ test('ref in root external multiple times', (t) => {
766766

767767
t.equal(output, '{"int":42}')
768768
})
769+
770+
test('ref external to relative definition', (t) => {
771+
t.plan(2)
772+
773+
const externalSchema = {
774+
'relative:to:local': {
775+
$id: 'relative:to:local',
776+
type: 'object',
777+
properties: {
778+
foo: { $ref: '#/definitions/foo' }
779+
},
780+
definitions: {
781+
foo: { type: 'string' }
782+
}
783+
}
784+
}
785+
786+
const schema = {
787+
type: 'object',
788+
required: ['foo'],
789+
properties: {
790+
fooParent: { $ref: 'relative:to:local' }
791+
}
792+
}
793+
794+
const object = { fooParent: { foo: 'bar' } }
795+
const stringify = build(schema, { schema: externalSchema })
796+
const output = stringify(object)
797+
798+
try {
799+
JSON.parse(output)
800+
t.pass()
801+
} catch (e) {
802+
t.fail()
803+
}
804+
805+
t.equal(output, '{"fooParent":{"foo":"bar"}}')
806+
})

0 commit comments

Comments
 (0)