-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathswagger2openapi.ts
51 lines (42 loc) · 1.72 KB
/
swagger2openapi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Command, Args } from '@oclif/core';
import * as SwaggerParser from '@apidevtools/swagger-parser';
import * as s2o from 'swagger2openapi';
import { promisify } from 'util';
import * as commonFlags from '../common/flags';
import { parseDefinition, OutputFormat, stringifyDocument, resolveDefinition } from '../common/definition';
export class Swagger2Openapi extends Command {
public static description = 'Convert Swagger 2.0 definitions to OpenAPI 3.0.x';
public static examples = [`$ openapi swagger2openapi --yaml ./swagger.json > openapi.yml`];
public static flags = {
...commonFlags.help(),
...commonFlags.parseOpts(),
...commonFlags.outputFormat(),
};
public static args = {
definition: Args.string({
description: 'input definition file'
})
}
public async run() {
const { args, flags } = await this.parse(Swagger2Openapi);
const { dereference, bundle, validate, header, root, strip } = flags;
// parse definition
const definition = resolveDefinition(args.definition);
if (!definition) {
this.error('Please load a definition file', { exit: 1 });
}
const swagger = await parseDefinition({ definition, dereference, bundle, validate, header, root, strip });
// convert to swagger
let document: SwaggerParser.Document;
try {
const convertOptions = {}; // @TODO: take in some flags?
const converted = await promisify(s2o.convertObj)(swagger, convertOptions);
document = converted.openapi;
} catch (err) {
this.error(err, { exit: 1 });
}
// output in correct format
const format = flags.format === 'json' || flags.json ? OutputFormat.JSON : OutputFormat.YAML;
this.log(stringifyDocument({ document, format }));
}
}