-
Notifications
You must be signed in to change notification settings - Fork 6
/
smart-publish.js
42 lines (39 loc) · 1.4 KB
/
smart-publish.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
Meteor.smartPublish = function(name, callback) {
Meteor.publish(name, function() {
var publication = this;
var collections = {};
function getCollectionByName(name) {
return collections[name] = collections[name] || new Collection(name);
}
publication.getCollectionByName = getCollectionByName;
function Collection() {
BaseCollection.apply(this, arguments);
}
Collection.prototype = Object.create(BaseCollection.prototype);
Collection.prototype.publication = publication;
publication.addDependency = function(name, fields, callback) {
if (!_.isArray(fields)) fields = [fields];
var relations = getCollectionByName(name).relations;
var dep = new Dependency(callback);
fields.forEach(function(field) {
if (field.indexOf(".") != -1) { // See #8
field = field.substr(0, field.indexOf("."));
}
relations[field] = relations[field] || [];
relations[field].push(dep);
});
}
var context = Object.create(publication);
_.extend(context, new CallbacksWrapper(getCollectionByName));
context.ready = undefined;
var cursors = callback.apply(context, arguments);
var wrappers = getWrappersFromCallbackResult(getCollectionByName, cursors);
wrappers.push(context);
this.ready();
this.onStop(function() {
_.forEach(wrappers, function(x) {
x.stop();
});
});
});
}