From 97511ba920ff0649d28404329d4017571f5fefdc Mon Sep 17 00:00:00 2001 From: Ivan Tymoshenko Date: Fri, 20 Oct 2023 22:12:03 +0200 Subject: [PATCH] feat: add hasSchema method --- index.js | 4 ++++ test/has-schema.test.js | 28 ++++++++++++++++++++++++++++ types/index.d.ts | 7 +++++++ types/index.test-d.ts | 2 ++ 4 files changed, 41 insertions(+) create mode 100644 test/has-schema.test.js diff --git a/index.js b/index.js index c7a0c7e..c86fe77 100644 --- a/index.js +++ b/index.js @@ -41,6 +41,10 @@ class RefResolver { return getDataByJSONPointer(schema.schema, jsonPointer) } + hasSchema (schemaId) { + return this.#schemas[schemaId] !== undefined + } + getSchemaRefs (schemaId) { const schema = this.#schemas[schemaId] if (schema === undefined) { diff --git a/test/has-schema.test.js b/test/has-schema.test.js new file mode 100644 index 0000000..490df29 --- /dev/null +++ b/test/has-schema.test.js @@ -0,0 +1,28 @@ +'use strict' + +const assert = require('node:assert/strict') +const { test } = require('node:test') +const { RefResolver } = require('../index.js') + +test('should return true if schema exists', () => { + const refResolver = new RefResolver() + + const schemaId = 'schemaId' + const schema = { + $id: 'schemaId', + type: 'object', + properties: { + foo: { type: 'string' } + } + } + refResolver.addSchema(schema) + + const hasSchema = refResolver.hasSchema(schemaId) + assert.strictEqual(hasSchema, true) +}) + +test('should return false if schema does not exist', () => { + const refResolver = new RefResolver() + const hasSchema = refResolver.hasSchema('schemaId') + assert.strictEqual(hasSchema, false) +}) diff --git a/types/index.d.ts b/types/index.d.ts index 7cba5a5..fffbb7a 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -27,6 +27,13 @@ declare class RefResolver { */ getSchema(schemaId: string, jsonPointer?: string): any | null; + /** + * Returns true if the schema by the given schema id is added to the resolver. + * @param {string} schemaId - The schema id of the schema to be checked. + * @returns {boolean} True if the schema by the given schema id is added to the resolver. + */ + hasSchema(schemaId: string): boolean; + /** * Returns the schema references of the schema by the given schema id. * @param {string} schemaId - The schema id of the schema whose references are to be returned. diff --git a/types/index.test-d.ts b/types/index.test-d.ts index 670ec08..9de4ed4 100644 --- a/types/index.test-d.ts +++ b/types/index.test-d.ts @@ -11,6 +11,8 @@ expectType(resolver.addSchema({}, 'schemaId')) expectType(resolver.getSchema('schemaId')) expectType(resolver.getSchema('schemaId', 'jsonPointer')) +expectType(resolver.hasSchema('schemaId')) + expectType<{ schemaId: string; jsonPointer: string }[]>(resolver.getSchemaRefs('schemaId')) expectType<{ [key: string]: any }>(resolver.getSchemaDependencies('schemaId'))