Publish Collections Based on URL in Meteor.js
-
21-12-2019 - |
题
Pseudocode:
Meteor.publish 'stuff', ->
if this.userId
return doStuffForLoggedInUsers(this.userId)
else if url matches '/some_url/:user_api_key'
return doStuffForApiKey(apiKey)
else
return null
A solution using Iron Router would be optimal, but a non routing framework solution would also help.
解决方案
Perhaps something like this:
client
Router.map(function() {
this.route('postsWithKey', {
path: '/posts/:apiKey',
template: 'posts',
before: function() {
this.subscribe('posts', this.params.apiKey);
}
});
return this.route('posts', {
before: function() {
this.subscribe('posts');
}
});
});
server
Meteor.publish('posts', function(apiKey) {
check(apiKey, Match.Optional(String));
if (apiKey) {
return Posts.find({key: apiKey});
} else if (this.userId) {
return Posts.find({owner: this.userId});
}
});
When the route with an api key is run, the client will activate the posts
subscription with the key. On the server, one cursor is returned if the key exists, otherwise a different cursor is returned if the user is logged in. You could do more sophisticated validation of the key - e.g. throw an error if it doesn't exist in the database.
不隶属于 StackOverflow