From 384133f11448cac942e6339f106f8b15750d929f Mon Sep 17 00:00:00 2001 From: Oprysk Date: Wed, 19 Jan 2022 19:43:23 +0200 Subject: [PATCH] fix: definition name util --- src/utils/__tests__/openapi.test.ts | 11 +++++++++++ src/utils/openapi.ts | 9 +++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/utils/__tests__/openapi.test.ts b/src/utils/__tests__/openapi.test.ts index 1e4adaef..dde44fdd 100644 --- a/src/utils/__tests__/openapi.test.ts +++ b/src/utils/__tests__/openapi.test.ts @@ -12,6 +12,7 @@ import { sortByRequired, humanizeNumberRange, getContentWithLegacyExamples, + getDefinitionName, } from '../'; import { FieldModel, OpenAPIParser, RedocNormalizedOptions } from '../../services'; @@ -1269,4 +1270,14 @@ describe('Utils', () => { expect(content['text/plain']).toStrictEqual(info.content['text/plain']); }); }); + + describe('getDefinitionName', () => { + test('should return the name if pointer match regex', () => { + expect(getDefinitionName('#/components/schemas/Call')).toEqual('Call'); + }); + test("should return the `undefined` if pointer not match regex or it's absent", () => { + expect(getDefinitionName('#/test/path/Call')).toBeUndefined(); + expect(getDefinitionName()).toBeUndefined(); + }); + }); }); diff --git a/src/utils/openapi.ts b/src/utils/openapi.ts index 9312e3fb..fc3cc3b2 100644 --- a/src/utils/openapi.ts +++ b/src/utils/openapi.ts @@ -384,14 +384,15 @@ export function langFromMime(contentType: string): string { return 'clike'; } +const DEFINITION_NAME_REGEX = /^#\/components\/(schemas|pathItems)\/([^/]+)$/; + export function isNamedDefinition(pointer?: string): boolean { - return /^#\/components\/(schemas|pathItems)\/[^\/]+$/.test(pointer || ''); + return DEFINITION_NAME_REGEX.test(pointer || ''); } export function getDefinitionName(pointer?: string): string | undefined { - if (!pointer) return undefined; - const match = pointer.match(/^#\/components\/(schemas|pathItems)\/([^\/]+)$/); - return match === null ? undefined : match[1]; + const [name] = pointer?.match(DEFINITION_NAME_REGEX)?.reverse() || []; + return name; } function humanizeMultipleOfConstraint(multipleOf: number | undefined): string | undefined {