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 committed Aug 2, 2024
1 parent 32fc75d commit 4353d87
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/parser/spec.js
Original file line number Diff line number Diff line change
@@ -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;
};
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 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: {
Expand Down

0 comments on commit 4353d87

Please sign in to comment.