Truly isomorphic publications
Meteor methods already have it: when you publish a method, it is immediately available both on the client and on the server, with the same signature.
Meteor.methods({
newPost({title, content}) {
if (Meteor.userId()) {
Posts.insert({
userId: Meteor.userId(),
title,
content,
});
}
}
});
Meteor.call("newPost", {
title: "Hello world",
content: "Lorem ipsum",
});
With publications the situation is different: after you register a publication you can’t just call a publication to get reactive data. You have to subscribe, and then fetch the data, which leads to boilerplate code and logic duplication.
Meteor.publish("myPosts", function({limit}) {
return Posts.find({
userId: this.userId,
}, {
limit
});
});/* Later */// Boilerplate
const handle = Meteor.subscribe("myPosts", {limit});
if (handle.ready()) { // Code duplication
return Posts.find({
userId: Meteor.userId()
}, {
limit
});
}
But what if you could publish a function and then subscribe to the function’s result directly, no matter whether you are on the client or on the server?
publish("myPosts", function({userId}, {limit}) {
return Posts.find({
userId,
}, {
limit
});
});/* Later */
return subscribe("myPosts", {limit});
Well, now you can, with the functions defined in this gist. Let me know what you think in the comments :)