-
Notifications
You must be signed in to change notification settings - Fork 78
/
serve.js
74 lines (62 loc) · 2.03 KB
/
serve.js
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
#!/usr/bin/env node
'use strict';
const express = require('express');
const path = require('path');
const config = require('./lib/config.js');
const loader = require('./lib/loader.js');
const server = require('./lib/server.js');
const fromJsonSchema = require('json-schema-to-openapi-schema');
const DEFAULT_PORT = 5000;
const htmlOrError = specFile => {
try {
return server.loadHTML(specFile);
}
catch (e) {
console.error('Failed to load HTML file: ' + e.message);
process.exit(1);
}
}
const launchServer = (app, port, specFile, { verbose }) => {
app.listen(port, () => {
if (verbose > 0) {
console.log(`API specifications server running!`);
console.log(`HTML: http://localhost:${port}`);
console.log(`JSON Specs: http://localhost:${port}/spec.json`);
}
}).on('error', e => {
console.error('Failed to start server: ' + e.message);
process.exit(1);
});
}
const command = async (specFile, cmd) => {
config.init(cmd);
const jsonSchema = config.get('jsonSchema');
const verbose = config.get('quiet') ? 0 : config.get('verbose', 1);
const port = config.get('serve:port', DEFAULT_PORT);
const app = express();
const bundleDir = path.dirname(require.resolve('redoc'));
const html = htmlOrError(specFile);
const spec = await loader.readOrError(
specFile,
buildLoaderOptions(jsonSchema, verbose)
);
app.use('/assets/redoc', express.static(bundleDir));
app.get('/spec.json', (req, res) => {
res.header('content-type', 'application/vnd.oai.openapi+json');
res.send(JSON.stringify(spec));
});
app.get('/', (req, res) => {
res.send(html);
});
launchServer(app, port, specFile, { verbose });
}
const buildLoaderOptions = (jsonSchema, verbose) => {
const options = {
resolve: true,
verbose,
filters: [],
};
if (jsonSchema) options.filters.push(fromJsonSchema);
return options;
}
module.exports = { command };