伪代码:
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
使用 Iron Router 的解决方案是最佳选择,但非路由框架解决方案也会有所帮助。
最佳答案
也许是这样的:
客户端
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');
}
});
});
服务器
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});
}
});
<小时/>
当带有 api key 的路由运行时,客户端将使用该 key 激活 posts
订阅。在服务器上,如果 key 存在,则返回一个游标,否则,如果用户登录,则返回不同的游标。您可以对 key 进行更复杂的验证 - 例如如果数据库中不存在则抛出错误。
关于javascript - 在 Meteor.js 中基于 URL 发布集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22028665/