oortcloud/node-ddp-client

DDP Client emits message before modifying collections.

Closed this issue · 4 comments

Shouldn't it modify collections before notifying listeners that changes have occurred?

To be similar to normal Meteor ddp updates, it might make sense to update the collections so that when listening to changes on a collection, or additions to a collection, ddpclient.collections can be checked and have the new data present.

See: https://github.com/serviewcare/node-ddp-client

The idea here is to allow the app to make changes to the message before it is applied to the collection. From the original commit (by @cmather):

Add message filters.

Message filters are functions that get called when a message is
received. All message filter functions are called before the ddp message
is processed with the DDPClient.prototype._message method which is
guaranteed to be called last.

Message filters can be added in the constructor function options hash or
by calling the onMessage method with the function passed as a parameter.
The callback function takes two parameters: data and flags. Its context
(this) will be the DDPClient.

I agree with you that it would be extremely useful to have a message emitted when the collection has been updated. Another solution would be to provide a reactive collection just like in meteor.

FYI - A very dirty workaround I ended up using is to wrap your code that needs to be executed after the collection is updated in a setTimeout(function() { /* your code */ }, 0):

I do not think we can change the way it is done now because too many projects rely on this but we could add another message executed when the callback is done. Maybe update?

One potential approach would be to allow the user to specify a callback after the subscription is created (so that the signature does not change). Javascript isn't my strong point, so can you see any issues that may come up with being able to add callbacks as shown below? I am willing to work on a patch towards this if you think this is a good idea.

e.g.

ddpclient.setSubscriptionCallback('posts', function(x) {...});
// callback variable x could contain metadata too, e.g. x.action, x.ddp_message, x.collection, etc...

Fixed via 48e8b33