From 73ea796eb76f93232995e9c7654fdaf06bd724dd Mon Sep 17 00:00:00 2001 From: Ivan Tymoshenko Date: Sun, 22 Oct 2023 10:47:39 +0200 Subject: [PATCH] fix: throw an error if target schema not found (#3) --- index.js | 6 ++++++ test/deref-schema.test.js | 42 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/index.js b/index.js index f5059c0..a912273 100644 --- a/index.js +++ b/index.js @@ -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 } diff --git a/test/deref-schema.test.js b/test/deref-schema.test.js index facfc58..2efd5d7 100644 --- a/test/deref-schema.test.js +++ b/test/deref-schema.test.js @@ -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".' + ) + } +})