This repository has been archived by the owner on Jan 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
69 lines (57 loc) · 1.6 KB
/
server.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
'use strict';
const config = require('./config');
const fs = require('fs');
const path = require('path');
const SwaggerHapi = require('swagger-hapi');
const Hapi = require('hapi');
function setupSwaggerUi(server) {
const swaggerUiPath = path.join(__dirname, './node_modules/swagger-ui/dist');
const indexPath = path.join(swaggerUiPath, 'index.html');
// Configure the Swagger file URL
const swaggerUiIndex = fs.readFileSync(indexPath, 'utf8');
const contents = swaggerUiIndex.replace(/url = ".+";/,
`url = "${config.url}/v1/swagger.yaml";`);
fs.writeFileSync(indexPath, contents, 'utf8');
server.route({
method: 'GET',
path: '/v1/docs/{param*}',
handler: {
directory: {
path: swaggerUiPath,
},
},
config: {
cache: {
expiresIn: 7 * 24 * 60 * 60 * 1000,
},
},
});
}
function startServer() {
const server = new Hapi.Server();
SwaggerHapi.create(config.swaggerHapi, (err, swaggerHapi) => {
if (err) { throw err; }
const port = config.port;
const plugins = [
swaggerHapi.plugin,
...config.hapi.plugins,
];
server.connection({
host: config.host,
port,
routes: {
cors: true,
},
});
server.address = () => ({ port });
server.register(plugins, (_err) => {
if (_err) { throw _err; }
setupSwaggerUi(server);
server.start(() => {
console.info('Server started at', server.info.uri); // eslint-disable-line no-console
});
});
});
return server;
}
module.exports = startServer(); // for testing