1 |
|
2 |
|
3 | import http from 'http'
|
4 | import express from 'express'
|
5 |
|
6 | import Module from './Module'
|
7 | import { ExtendedError } from './errorUtils'
|
8 |
|
9 | import type { $Application } from 'express'
|
10 |
|
11 | const { MODULE_NAME, log, warn, error, noteGauge, noteCount, trackOp } = new Module(__filename)
|
12 |
|
13 | export default class ExpressApp {
|
14 |
|
15 |
|
16 | expressApp: $Application
|
17 | expressServer: ?Object
|
18 |
|
19 |
|
20 | constructor() {
|
21 | this.expressApp = express()
|
22 | }
|
23 |
|
24 |
|
25 | start = async (port: number) => {
|
26 | noteCount('ServerStart')
|
27 |
|
28 | await this.initExpress()
|
29 |
|
30 |
|
31 | this.expressServer = await new Promise((res, rej) => {
|
32 | const server = http.createServer(this.expressApp)
|
33 | server.on('error', (err: Error) => {
|
34 | rej(new ExtendedError('Failed to start server', { err }))
|
35 | })
|
36 | server.on('listening', () => {
|
37 | log('Server started', { port: port })
|
38 | res(server)
|
39 | })
|
40 | server.listen(port, undefined);
|
41 | })
|
42 |
|
43 | }
|
44 |
|
45 | stop = async () => {
|
46 | if (this.expressServer) {
|
47 |
|
48 | await new Promise((resp, rej) => this.expressServer.close((err) => err ? rej(err) : resp()))
|
49 | this.expressServer = null
|
50 | }
|
51 | noteCount('ServerStop')
|
52 | log('Server stopped')
|
53 | }
|
54 |
|
55 | initExpress = async () => { }
|
56 | }
|