流星子/酒吧与模拟酒吧很慢更新
问题描述:
我有一个酒吧,包装和外部的API。客户端是外部API客户端。有一个“激活”按钮,他们可以推动激活计费方法。按钮调用更新集合的更新方法。该pub会更新外部api。模拟运行并更新客户端集合。按钮按预期变为“DEACTIVATE”。这是问题出现的地方。外部api需要一些时间才能返回更新的文档。在转到“DEACTIVATE”的按钮的100-200ms内,它将回到'ACTIVATE',然后500ms后回到'DEACTIVATE',它应该假定外部API没有问题。流星子/酒吧与模拟酒吧很慢更新
我敢肯定,我可以想出一些hacky解决方案来处理客户端中的这个问题,但是想知道是否有办法告诉模拟/客户端集合酒吧很慢并且不经常更新?因此,给pub/external api更多时间来完成它的更新。
答
事实证明这非常简单。
仅客户端模拟是不够的。诀窍是做服务器端模拟。为了完成这个第一次设置一个钩子Meteor.publish这个对象是这样的。
_initServer() {
if (Meteor.isServer) {
console.log(`Server initializing external collection "${this.name}"`)
let self = this
Meteor.publish(this.name, function (selector, options) {
check(selector, Match.Optional(Match.OneOf(undefined, null, Object)))
check(options, Match.Optional(Match.OneOf(undefined, null, Object)))
self.publication = this
self._externalApi.fetchAll()
.then((docs)=>docs.forEach((doc)=>this.added(self.name, doc._id, doc)))
.then(()=>this.ready())
// todo handle error
.catch((error)=>console.error(`${self.name}._initServer: self._externalApi.fetchAll`, error))
})
}
}
然后在你的更新功能,你可以在客户端和服务器上的模拟像这样:
this.update = new ValidatedMethod({
name: `${self.name}.update`,
validate: (validators && validators.update) ? validators.update : self.updateSchema.validator({clean: true}),
run(doc) {
console.log(`${self.name}.update `, doc)
if (Meteor.isServer && self._externalApi.update) {
// server side simulation
self.changed(doc)
self._externalApi.update(doc._id, doc)
.then(self.changed)
.catch((error)=>handleError(`${self.name}.update`, 'externalApi.update', error))
} else {
// client side simulation
self.collection.update(doc._id, {$set: doc})
}
},
})
道歉,如果这是在简化这些例子都是从我们使用外部API的一个大型图书馆。
你好,迈克尔。我用'future.js'解决了类似的问题。 [在这里查看](https://github.com/laverdet/node-fibers)。另外,你能否发布你的发布/订阅代码和外部API调用?也许这可能有助于回答这个问题。 –
Meteor API中有一些特定的方法可以处理这种情况。发布你的酒吧/子代码和相关的客户代码,我可以提供一些帮助。 – jordanwillis
希望避免代码发布,但我会建立一个MVP并在第二或第二天发布。我们已经构建了一个类来封装外部API,并使用许多其他库。谢谢,我会尽快解决问题的。 –