forked from mcollina/multines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultines.js
102 lines (79 loc) · 2.39 KB
/
multines.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use strict'
const util = require('util')
const mqemitter = require('mqemitter')
const redis = require('mqemitter-redis')
const mongodb = require('mqemitter-mongodb')
const kDeliver = Symbol.for('deliver')
function buildDeliver (socket, topic) {
return async function deliver (message, done) {
if (topic === message.topic) {
await socket.publish('/' + topic, message.body)
} else {
await socket.publish('/' + topic, message)
}
}
}
function getMq (options) {
let mq
switch (options.type) {
case 'redis':
mq = redis(options)
break
case 'mongo':
case 'mongodb':
mq = mongodb(options)
break
default: {
mq = options.mq || mqemitter(options)
}
}
return {
removeListener: util.promisify(mq.removeListener.bind(mq)),
on: util.promisify(mq.on.bind(mq)),
emit: util.promisify(mq.emit.bind(mq)),
close: util.promisify(mq.close.bind(mq))
}
}
async function register (server, options) {
server.dependency('nes')
const mq = getMq(options)
server.decorate('server', 'subscriptionFar', (path, options) => {
options = options || {}
const wrapSubscribe = options.onSubscribe || (async (socket, path, params) => null)
const wrapUnsubscribe = options.onUnsubscribe || (async (socket, path, params) => null)
options.onSubscribe = async (socket, path, params) => {
const deliverMap = socket[kDeliver] || {}
socket[kDeliver] = deliverMap
const topic = path.replace(/^\//, '')
if (!deliverMap[path]) {
deliverMap[path] = buildDeliver(socket, topic)
}
await wrapSubscribe(socket, path, params)
await mq.on(topic, deliverMap[path])
}
options.onUnsubscribe = async (socket, path, params) => {
await wrapUnsubscribe(socket, path, params)
const deliverMap = socket[kDeliver] || {}
socket[kDeliver] = deliverMap
if (!deliverMap[path]) {
return
}
await mq.removeListener(path.replace(/^\//, ''), deliverMap[path])
}
server.subscription(path, options)
})
server.decorate('server', 'publishFar', async (path, body) => {
options = options || {}
await mq.emit({
topic: path.replace(/^\//, ''), // the first is always a '/'
body
})
})
server.ext('onPostStop', async () => {
await mq.close()
})
}
module.exports.register = register
register.attributes = {
pkg: require('./package.json')
}