forked from vol7/feathers-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongodb.js
More file actions
59 lines (51 loc) · 1.82 KB
/
Copy pathmongodb.js
File metadata and controls
59 lines (51 loc) · 1.82 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var mubsub = require('mubsub');
var debug = require('debug')('feathers-sync');
var omit = require('lodash').omit;
module.exports = function (config) {
debug('setting up database %s', config.db);
var client = mubsub(config.db, config.mubsub);
var channel = client.channel(config.collection || 'events', omit(config, ['mubsub', 'db', 'collection']));
return function () {
var oldSetup = this.setup;
this.setup = function () {
var result = oldSetup.apply(this, arguments);
var services = this.services;
Object.keys(services).forEach(function (path) {
var service = services[path];
service._serviceEvents.forEach(function (event) {
var ev = path + ' ' + event;
debug('subscribing to handler %s', ev);
channel.subscribe(ev, function (data) {
debug('got event, calling old emit %s', ev);
service._emit.call(service, event, data); // eslint-disable-line no-useless-call
});
});
});
return result;
};
function configurePlugin (service, path) {
if (typeof service.emit !== 'function' || typeof service.on !== 'function') {
return;
}
// Store the old emit method
service._emit = service.emit;
// Override an emit that publishes to the hub
service.mixin({
emit: function (ev, data) {
var event = path + ' ' + ev;
debug('emitting event to channel %s', event);
return channel.publish(event, data);
}
});
}
if (this.version && parseInt(this.version, 10) >= 3) {
this.mixins.push(configurePlugin);
}
else {
this.providers.push((path, service) => configurePlugin(service, path));
}
if (typeof config.connect === 'function') {
channel.connection.once('connect', config.connect);
}
};
};