From 7f1132a0fb3fa94b21199a939b5ce6ae799d21f2 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 | 30 ++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/parser/spec.js b/src/parser/spec.js index 8674007..8acd3f6 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 (majorVersion < 3 || majorVersion >= 4) { + throw new TypeError(`Unsupported OpenAPI version: ${spec.openapi ?? 'n/a'}`); + } + + return spec; }; diff --git a/src/parser/spec.test.js b/src/parser/spec.test.js index 0023c2f..4369d53 100644 --- a/src/parser/spec.test.js +++ b/src/parser/spec.test.js @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; import { validateSpec } from './spec.js'; +import { version } from 'eslint-plugin-prettier'; describe('validateSpec()', () => { it('should throw for invalid options', async () => { @@ -9,6 +10,35 @@ describe('validateSpec()', () => { ); }); + it('should throw an error on Swagger 2.0 spec', async () => { + const spec = { + info: { + title: 'Title', + version: '1' + }, + paths: {}, + swagger: '2.0' + }; + + await expect(validateSpec({ spec })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0/); + }); + + it('should throw an error on unsupported OpenAPI versions', async () => { + const spec1 = { + info: {}, + openapi: '2.0.0', + paths: {} + }; + const spec2 = { + info: {}, + openapi: '4.0.0', + paths: {} + }; + + await expect(validateSpec({ spec: spec1 })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0\.0/); + await expect(validateSpec({ spec: spec2 })).rejects.toThrowError(/Unsupported OpenAPI version: 4\.0\.0/); + }); + it('should return a parsed spec', async () => { const spec = { info: {