-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathserver.js
64 lines (52 loc) · 1.5 KB
/
server.js
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
'use strict'
const net = require('net')
const debug = require('debug')('abci')
const Connection = require('./connection.js')
function createServer (app) {
let server = net.createServer((client) => {
client.name = `${client.remoteAddress}:${client.remotePort}`
let conn = new Connection(client, async (req, cb) => {
let [ type ] = Object.keys(req)
let message = req[type]
// special messages
if (type === 'flush') {
conn.write({ flush: {} })
return cb()
} else if (type === 'echo') {
conn.write({ echo: { message: message.message } })
return cb()
}
let succeed = (response) => {
// respond to client
let message = { [type]: response }
conn.write(message)
cb()
}
let fail = (err) => {
// if app throws an error, send an 'exception' response
// and close the connection
debug(`ABCI error on "${type}":`, err)
message = { exception: { error: err.toString() } }
conn.write(message)
conn.close()
}
// message handler not implemented in app, send emtpy response
if (app[type] == null) {
return succeed({})
}
// call method
try {
let res = app[type](message)
// method can optionally be async
if (res instanceof Promise) {
res = await res
}
succeed(res)
} catch (err) {
fail(err)
}
})
})
return server
}
module.exports = createServer