Skip to content

Commit

Permalink
fix: throw an error if target schema not found (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-tymoshenko authored Oct 22, 2023
1 parent 33db77f commit 73ea796
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,12 @@ class RefResolver {
} = this.#parseSchemaRef(ref.ref, ref.sourceSchemaId)

const targetSchema = this.getDerefSchema(refSchemaId, refJsonPointer)
if (targetSchema === null) {
throw new Error(
`Cannot resolve ref "${ref.ref}". Ref "${refJsonPointer}" is not found in schema "${refSchemaId}".`
)
}

ref.targetSchema = targetSchema
ref.targetSchemaId = refSchemaId
}
Expand Down
42 changes: 42 additions & 0 deletions test/deref-schema.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,45 @@ test('should clone schema without refs', () => {
}
})
})

test('should throw if target ref schema is not found', () => {
const inputSchema = {
$id: 'http://example.com/root.json',
definitions: {
A: { $id: '#foo' },
B: {
$id: 'other.json',
definitions: {
X: { $id: '#bar', type: 'string' },
Y: { $id: 't/inner.json' }
}
},
C: {
$id: 'urn:uuid:ee564b8a-7a87-4125-8c96-e9f123d6766f',
type: 'object'
}
}
}

const addresSchema = {
$id: 'relativeAddress', // Note: prefer always absolute URI like: http://mysite.com
type: 'object',
properties: {
zip: { $ref: 'urn:uuid:ee564b8a-7a87-4125-8c96-e9f123d6766f' },
city2: { $ref: '#foo' }
}
}

const refResolver = new RefResolver()
refResolver.addSchema(inputSchema)
refResolver.addSchema(addresSchema)

try {
refResolver.derefSchema('relativeAddress')
} catch (error) {
assert.strictEqual(
error.message,
'Cannot resolve ref "#foo". Ref "#foo" is not found in schema "relativeAddress".'
)
}
})

0 comments on commit 73ea796

Please sign in to comment.