Repository navigation
Expand file tree
/
Copy pathServer.ts
More file actions
67 lines (53 loc) · 1.65 KB
/
Copy pathServer.ts
File metadata and controls
67 lines (53 loc) · 1.65 KB
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
import http from 'http'
import express from 'express'
import { Lincoln } from '@nnode/lincoln'
import { Merge, DeepPartial, Runnable } from '@nnode/core'
import { ServerConfig } from './ServerConfig'
export const ServerConfigurationType = Symbol('ServerConfiguration')
export abstract class Server<T extends ServerConfig> implements Runnable {
readonly config: T
readonly name: string
readonly server: http.Server
protected readonly app: express.Express
protected readonly log: Lincoln
constructor(name: string, app: express.Express, logger: Lincoln, config: DeepPartial<T>) {
this.name = name
this.log = logger.extend(name)
this.config = Merge<T>([config])
this.app = app
this.app.use(express.urlencoded({ extended: true }))
this.app.use(express.json())
this.server = http.createServer(this.app)
this.log.debug('create', this.name)
}
async initialize(): Promise<void> {
try {
this.config.statics.map((dir) => {
this.log.debug('using static folder:', dir)
express.static(dir)
})
await this.bootstrap(this.app)
} catch (error) {
console.error(error)
throw error
}
}
start(): Promise<void> {
return new Promise((resolve) => {
this.server.listen(this.config.port, () => resolve())
console.log(`listening ${this.config.host}:${this.config.port}`)
})
}
stop(): Promise<void> {
return new Promise((resolve, reject) => {
this.server.close((error) => {
if (error) {
reject(error)
} else {
resolve()
}
})
})
}
protected abstract bootstrap(app: express.Express): Promise<void>
}