事实证明这非常简单。
仅客户端模拟是不够的。诀窍是做服务器端模拟。为了完成这个第一次设置一个钩子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,并使用许多其他库。谢谢,我会尽快解决问题的。 –