forked from Matthew-Smith/general-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
75 lines (59 loc) · 1.72 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
70
71
72
73
74
75
/* eslint no-process-exit: "off", no-process-env: "off" */
import { once } from 'events';
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(/^@[\dA-Za-z-]+\//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);
this.server.listen(this.config.PORT);
await once(this.server, 'listening');
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();
if (this.server) {
this.server.close();
await once(this.server, 'close');
}
}
}
export default Server;