-
Notifications
You must be signed in to change notification settings - Fork 16
/
server.ts
69 lines (55 loc) · 1.71 KB
/
server.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
/* eslint no-process-exit: "off", no-process-env: "off" */
import Promise from 'bluebird';
import express, { Express } from 'express';
import fs from 'fs';
import http from 'http';
import https from 'https';
import { ExpressMiddleware, ServiceManager } from './backend';
import log from './logger';
import pjson from './package.json';
import { Config } from './types';
const name = pjson.name.replace(/^@[a-zA-Z0-9-]+\//g, '');
/**
* @class
*/
class Server {
app: Express | null = null;
server: https.Server | http.Server | null = null;
constructor(public serviceManager: ServiceManager, public config: Config) {}
/**
* Start server
* - Creates express app and services
*/
async start() {
// Start services.
await this.serviceManager.start();
this.app = express();
if (process.env.NODE_ENV === 'e2e') {
this.server = https.createServer(
{
key: fs.readFileSync('./certs/localhost.key'),
cert: fs.readFileSync('./certs/localhost.crt'),
requestCert: false,
rejectUnauthorized: false,
},
this.app
);
} else {
this.server = http.createServer(this.app);
}
const { middlewares, controllers } = this.serviceManager;
ExpressMiddleware.attach(this.app, middlewares, controllers);
await Promise.fromCallback((cb: any) => this.server!.listen(this.config.PORT, cb));
log.info(`[http] ${name} listening ${log.vars({ port: this.config.PORT })}`);
}
/**
* Stop server
* - Stops services first, then server
*/
async stop() {
// Stop services
await this.serviceManager.stop();
await Promise.fromCallback((cb) => this.server && this.server.close(cb));
}
}
export default Server;