Skip to content

Commit 82238f4

Browse files
Added support for Swagger 2 documents:
The support for Swagger 2 is done via file conversion instead adapter - Detected document version in file-reader - Added swagger2openapi which convert from Swagger 2 to 3
1 parent 95a020e commit 82238f4

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
"js-yaml": "^3.14.1",
6565
"mkdir-recursive": "^0.4.0",
6666
"mustache": "^3.0.1",
67+
"swagger2openapi": "^7.0.4",
6768
"yargs": "^12.0.5"
6869
},
6970
"devDependencies": {

src/services/parsers/file-reader.service.ts

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import {
1010
} from '../../utils/files.util';
1111
import { isURL } from '../../utils/string.util';
1212

13+
const versionRegx = /^([0-9]+)/;
14+
1315
/**
1416
* Main calss which parse the JSON/YAML file
1517
* If the file is a URL, it will download
@@ -30,7 +32,8 @@ export class FileReaderService {
3032

3133
async readFile(): Promise<OpenAPIV3.Document> {
3234
await this.prepareFile();
33-
this._document = await this.parseFile();
35+
const document = await this.parseFile();
36+
this._document = await this.upgradeFile(document);
3437
return this.document;
3538
}
3639

@@ -51,6 +54,35 @@ export class FileReaderService {
5154
console.info('');
5255
}
5356

57+
async upgradeFile(document: any): Promise<OpenAPIV3.Document> {
58+
let version: string;
59+
if (document.openapi) {
60+
version = versionRegx.exec(document.openapi)[1];
61+
} else if (document.swagger) {
62+
version = versionRegx.exec(document.swagger)[1];
63+
}
64+
65+
if (!version) {
66+
throw 'This is not a valid OpenApi/Swagger document';
67+
}
68+
69+
console.info('Swagger/API version detected:', version);
70+
switch (version) {
71+
case '3':
72+
return document;
73+
case '2':
74+
console.info('Convertin to OpenAPI V3');
75+
const converter = require('swagger2openapi');
76+
const converted = await converter.convertObj(document, {
77+
patch: true,
78+
warnOnly: true,
79+
});
80+
return converted.openapi;
81+
default:
82+
throw 'This OpenAPi/Swagger version is not compatible with this tool';
83+
}
84+
}
85+
5486
private async prepareFile(): Promise<void> {
5587
let extension = fileExtension(this.path);
5688
if (!fileIsJSON(this.path) && !fileIsYAML(this.path)) {
@@ -70,7 +102,7 @@ export class FileReaderService {
70102
}
71103
}
72104

73-
private parseFile(): OpenAPIV3.Document {
105+
private parseFile(): any {
74106
const filePath = this.localFilePath;
75107
switch (fileExtension(filePath)) {
76108
case 'yaml':

0 commit comments

Comments
 (0)