-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathserver.ts
More file actions
43 lines (33 loc) · 1.02 KB
/
server.ts
File metadata and controls
43 lines (33 loc) · 1.02 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
import {Server as HTTPServer} from 'http'
import bodyParser = require('body-parser')
import express = require('express')
import {setSocketPath} from './dynamic'
import {getHandlerMethods, Handler, Keys} from './handler'
export class Server<RQ, RS, K extends Keys<RQ, RS> = Keys<RQ, RS>> {
private readonly app = express()
private readonly server: HTTPServer
constructor(name: string, handler: Handler<RQ, RS>) {
const app = this.app.use(bodyParser.json({limit: '10mb'}))
getHandlerMethods(handler).forEach(method =>
app.post(`/${method}`, async (req, res) => {
try {
const result = await handler[method as any as K](req.body.data)
res.json({result})
}
catch(error) {
const message = error && (error.stack || error.message || error)
res.json({
error: typeof message === 'string' ? message : 'Unknown error'
})
return
}
})
)
this.server = app
.listen(setSocketPath(name))
.on('error', err => console.error(err))
}
public close() {
this.server.close()
}
}