Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: throw an error if target schema not found #3

Merged
merged 3 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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".'
)
}
})