-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathswagger-editor.ts
81 lines (69 loc) · 2.5 KB
/
swagger-editor.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Command, Args } from '@oclif/core';
import * as fs from 'fs';
import * as path from 'path';
import * as Router from 'koa-router';
import * as serve from 'koa-static';
import axios from 'axios';
import { escapeStringTemplateTicks, parseHeaderFlag } from '../common/utils';
import * as commonFlags from '../common/flags';
import { startServer, createServer } from '../common/koa';
import { resolveDefinition } from '../common/definition';
function getAbsoluteFSPath() {
return path.dirname(require.resolve('swagger-editor-dist'));
}
export class SwaggerEditor extends Command {
public static description = 'Start a Swagger Editor instance';
public static examples = ['$ openapi swagger-editor', '$ openapi swagger-editor ./openapi.yml'];
public static flags = {
...commonFlags.help(),
...commonFlags.serverOpts(),
...commonFlags.header(),
};
public static args = {
definition: Args.string({
description: 'input definition file'
})
}
public async run() {
const { args, flags } = await this.parse(SwaggerEditor);
const { port, logger, header } = flags;
const definition = resolveDefinition(args.definition);
const app = createServer({ logger });
const router = new Router();
let document = null;
if (definition) {
if (definition.match('://')) {
const { data } = await axios.get(definition, {
headers: parseHeaderFlag(header),
responseType: 'text',
// need to set this, unfortunately
// https://github.com/axios/axios/issues/907
transformResponse: [(data) => data.toString()],
});
try {
// attempt to prettify JSON
document = JSON.stringify(JSON.parse(data), null, 2);
} catch (err) {
document = data;
}
} else {
document = fs.readFileSync(definition).toString();
}
}
const swaggerEditorRoot = getAbsoluteFSPath();
if (document) {
const indexHTML = fs.readFileSync(path.join(swaggerEditorRoot, 'index.html')).toString('utf8');
router.get('/', (ctx) => {
ctx.body = indexHTML.replace(
'window.editor = editor',
`editor.specActions.updateSpec(\`${escapeStringTemplateTicks(document)}\`)\n\nwindow.editor = editor`,
);
});
}
app.use(router.routes());
app.use(serve(swaggerEditorRoot));
const { port: portRunning } = await startServer({ app, port });
this.log(`Swagger Editor running at http://localhost:${portRunning}`);
this.log();
}
}