-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.js
50 lines (42 loc) · 911 Bytes
/
worker.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
'use strict'
const cluster = require('cluster')
const EventEmitter = require('events')
var pbx = new EventEmitter()
var msgNum = 0
cluster.worker.on('message', (msg) => {
if ((typeof(msg.from) !== 'undefined') && (msg.from === 'db')) {
pbx.emit(msg.id, msg)
}
})
function backendCall(method, params, cb) {
pbx.once(msgNum, (msg) => {
if (msg.error) {
cb(msg.error)
} else if (msg.result.length > 0) {
cb(null, ...msg.result)
} else {
cb()
}
})
cluster.worker.send({
target: 'db',
method: method,
params: params,
id: msgNum++
})
}
function m(name) {
return function () {
let orderedArgs = []
Object.keys(arguments).sort().forEach(k => {
orderedArgs.push(arguments[k])
})
let cb = orderedArgs.pop()
backendCall(name, orderedArgs, cb)
}
}
module.exports = {
put: m('put'),
get: m('get'),
del: m('del')
}