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 7f1132a
Show file tree
Hide file tree
Showing 2 changed files with 43 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;
};
30 changes: 30 additions & 0 deletions src/parser/spec.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { validateSpec } from './spec.js';
import { version } from 'eslint-plugin-prettier';

Check failure on line 3 in src/parser/spec.test.js

View workflow job for this annotation

GitHub Actions / tests

'version' is defined but never used

describe('validateSpec()', () => {
it('should throw for invalid options', async () => {
Expand All @@ -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: {
Expand Down

0 comments on commit 7f1132a

Please sign in to comment.