Skip to content

Commit 14a9991

Browse files
Eommmcollina
authored andcommitted
fix/$ref on root schema (#163)
* fix: $ref in root schema * add: multiple root $ref
1 parent 0d96f43 commit 14a9991

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

index.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ function build (schema, options) {
7171
`
7272
}
7373

74+
if (schema['$ref']) {
75+
schema = refFinder(schema['$ref'], schema, options.schema)
76+
}
77+
7478
if (schema.type === undefined) {
7579
schema.type = inferTypeByKeyword(schema)
7680
}
@@ -477,6 +481,10 @@ function refFinder (ref, schema, externalSchema) {
477481
// If external file
478482
if (ref[0]) {
479483
schema = externalSchema[ref[0]]
484+
485+
if (schema['$ref']) {
486+
return refFinder(schema['$ref'], schema, externalSchema)
487+
}
480488
}
481489

482490
var code = 'return schema'

test/ref.test.js

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -684,3 +684,85 @@ test('ref internal - multiple $ref format', (t) => {
684684

685685
t.equal(output, '{"zero":"test","a":"test","b":"test","c":"test","d":"test","e":"test"}')
686686
})
687+
688+
test('ref in root external', (t) => {
689+
t.plan(2)
690+
691+
const externalSchema = {
692+
numbers: {
693+
$id: 'numbers',
694+
definitions: {
695+
num: {
696+
type: 'object',
697+
properties: {
698+
int: {
699+
type: 'integer'
700+
}
701+
}
702+
}
703+
}
704+
}
705+
}
706+
707+
const schema = {
708+
title: 'object with $ref in root schema',
709+
type: 'object',
710+
$ref: 'numbers#/definitions/num'
711+
}
712+
713+
const object = { int: 42 }
714+
const stringify = build(schema, { schema: externalSchema })
715+
const output = stringify(object)
716+
717+
try {
718+
JSON.parse(output)
719+
t.pass()
720+
} catch (e) {
721+
t.fail()
722+
}
723+
724+
t.equal(output, '{"int":42}')
725+
})
726+
727+
test('ref in root external multiple times', (t) => {
728+
t.plan(2)
729+
730+
const externalSchema = {
731+
numbers: {
732+
$id: 'numbers',
733+
$ref: 'subnumbers#/definitions/num'
734+
},
735+
subnumbers: {
736+
$id: 'subnumbers',
737+
definitions: {
738+
num: {
739+
type: 'object',
740+
properties: {
741+
int: {
742+
type: 'integer'
743+
}
744+
}
745+
}
746+
}
747+
}
748+
}
749+
750+
const schema = {
751+
title: 'object with $ref in root schema',
752+
type: 'object',
753+
$ref: 'numbers#/definitions/num'
754+
}
755+
756+
const object = { int: 42 }
757+
const stringify = build(schema, { schema: externalSchema })
758+
const output = stringify(object)
759+
760+
try {
761+
JSON.parse(output)
762+
t.pass()
763+
} catch (e) {
764+
t.fail()
765+
}
766+
767+
t.equal(output, '{"int":42}')
768+
})

0 commit comments

Comments
 (0)