diff --git a/README.md b/README.md index e2177a1..b4bee09 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A plugin for [Fastify](https://fastify.dev) to connect routes with a OpenAPI 3.x specification. It does so by: - Providing a way to register routes using the `operationId` defined in your specification instead of having to manually call `fastify.route` with the correct URL, method, and schema. -- Handling `securitySchemes` and `security` keywords defined in your OpenAPI specification, simplifying the implementation of authentication and authorization middleware. +- Handling `securitySchemes` and `security` keywords defined in your specification, simplifying the implementation of authentication and authorization middleware. ## Installation diff --git a/src/parser/spec.js b/src/parser/spec.js index 8674007..2f2270b 100644 --- a/src/parser/spec.js +++ b/src/parser/spec.js @@ -1,5 +1,14 @@ import OpenAPIParser from '@readme/openapi-parser'; export const validateSpec = async options => { - return await OpenAPIParser.validate(options.spec); + const spec = await OpenAPIParser.validate(options.spec); + + const version = spec.openapi ?? spec.swagger; + const majorVersion = Number(version?.split?.('.')[0]); + + if (isNaN(majorVersion) || majorVersion < 3 || majorVersion >= 4) { + throw new TypeError(`Unsupported OpenAPI version: ${version ?? 'unknown'}`); + } + + return spec; }; diff --git a/src/parser/spec.test.js b/src/parser/spec.test.js index 0023c2f..4d16c2c 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 specSwagger2 = { + info: { + title: 'Title', + version: '1' + }, + paths: {}, + swagger: '2.0' + }; + const specOpenApi2 = { + info: {}, + openapi: '2.0.0', + paths: {} + }; + const specOpenApi4 = { + info: {}, + openapi: '4.0.0', + paths: {} + }; + + await expect(validateSpec({ spec: specSwagger2 })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0/); + await expect(validateSpec({ spec: specOpenApi2 })).rejects.toThrowError(/Unsupported OpenAPI version: 2\.0\.0/); + await expect(validateSpec({ spec: specOpenApi4 })).rejects.toThrowError(/Unsupported OpenAPI version: 4\.0\.0/); + }); + it('should return a parsed spec', async () => { const spec = { info: {