From 076392d95c0c31a15337774eb6c112d30fe7d4bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Cruz?= Date: Fri, 2 Aug 2024 21:51:10 +0100 Subject: [PATCH] Add error on unsupported OpenAPI versions --- src/parser/spec.js | 14 +++++++++++++- src/parser/spec.test.js | 25 +++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/src/parser/spec.js b/src/parser/spec.js index 8674007..86ca626 100644 --- a/src/parser/spec.js +++ b/src/parser/spec.js @@ -1,5 +1,17 @@ import OpenAPIParser from '@readme/openapi-parser'; export const validateSpec = async options => { - return await OpenAPIParser.validate(options.spec); + const spec = await OpenAPIParser.validate(options.spec); + + if (spec.swagger) { + throw new TypeError(`Unsupported OpenAPI version: ${spec.swagger}`); + } + + const majorVersion = Number(spec.openapi?.split('.')[0] ?? '0'); + + if (isNaN(majorVersion) || majorVersion < 3 || majorVersion >= 4) { + throw new TypeError(`Unsupported OpenAPI version: ${spec.openapi ?? 'unknown'}`); + } + + return spec; }; diff --git a/src/parser/spec.test.js b/src/parser/spec.test.js index 0023c2f..ff6b0aa 100644 --- a/src/parser/spec.test.js +++ b/src/parser/spec.test.js @@ -9,6 +9,31 @@ describe('validateSpec()', () => { ); }); + it('should throw an error on unsupported OpenAPI versions', async () => { + const specSwagger20 = { + info: { + title: 'Title', + version: '1' + }, + paths: {}, + swagger: '2.0' + }; + const specOpenApi20 = { + info: {}, + openapi: '2.0.0', + paths: {} + }; + const specOpenApi40 = { + info: {}, + openapi: '4.0.0', + paths: {} + }; + + await expect(validateSpec({ spec: specSwagger20 })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0/); + await expect(validateSpec({ spec: specOpenApi20 })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0\.0/); + await expect(validateSpec({ spec: specOpenApi40 })).rejects.toThrowError(/Unsupported OpenAPI version: 4\.0\.0/); + }); + it('should return a parsed spec', async () => { const spec = { info: {