事實證明這非常簡單。
僅客戶端模擬是不夠的。訣竅是做服務器端模擬。爲了完成這個第一次設置一個鉤子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,並使用許多其他庫。謝謝,我會盡快解決問題的。 –