-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
74 lines (58 loc) · 1.87 KB
/
index.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
var EventEmitter = require('events').EventEmitter
, inherits = require('util').inherits
var debug = require('debug')('subscription')
function Subscription (verifyer) {
if (!(this instanceof Subscription)) {
return new Subscription(verifyer)
}
EventEmitter.call(this)
if ('function' == typeof verifyer) {
this.verifyer = verifyer
}
}
inherits(Subscription, EventEmitter)
module.exports = Subscription
Subscription.prototype.verifyer = function (userToken, verifyToken, callback) {
callback(new Error('You must override Subscription#verifyer()'))
}
Subscription.prototype.dispatcher = function () {
var self = this
return function (req, res) {
res.send(200)
var notification = req.body
debug('got notification')
if (!notification) return
if (!notification.collection) return
if (!notification.operation) return
if (!notification.userToken) return
if (!notification.verifyToken) return
self.verifyer(notification.userToken, notification.verifyToken,
function (err, user) {
if (err) {
debug('error when verifying user')
console.error(err.stack || err)
return
}
if (!user) {
debug('invalid token %s, %s',
notification.userToken, notification.verifyToken)
return
}
var eventName = notification.collection + '#' + notification.operation
if (notification.userActions) {
notification.userActions.forEach(function (action) {
eventName += ':' + action.type
if (action.payload) {
eventName += '(' + action.payload + ')'
}
debug('emit %s for user %s', eventName, user.id)
self.emit(eventName, notification, user)
})
}
else {
debug('emit %s for user %s', eventName, user.id)
self.emit(eventName, notification, user)
}
})
}
}