Skip to content

Commit

Permalink
Add error on unsupported OpenAPI versions
Browse files Browse the repository at this point in the history
  • Loading branch information
satazor authored and andreffvalente committed Aug 2, 2024
1 parent 2b9f0c6 commit 5952fd9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 10 additions & 1 deletion src/parser/spec.js
Original file line number Diff line number Diff line change
@@ -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;
};
25 changes: 25 additions & 0 deletions src/parser/spec.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down

0 comments on commit 5952fd9

Please sign in to comment.