diff --git a/lib/publication.js b/lib/publication.js index e1a94c3..d6f020f 100644 --- a/lib/publication.js +++ b/lib/publication.js @@ -33,22 +33,11 @@ class Publication { // It's only needed when publish is being recursively run. this.observeHandle = this.cursor.observe({ added: Meteor.bindEnvironment(async (doc) => { - const addedPromise = new Promise(async (resolve) => { - const alreadyPublished = this.publishedDocs.has(doc._id) - - if (alreadyPublished) { - debugLog('Publication.observeHandle.added', `${collectionName}:${doc._id} already published`) - this.publishedDocs.unflagForRemoval(doc._id) - this._republishChildrenOf(doc) - this.subscription.changed(collectionName, doc._id, doc) - } else { - this.publishedDocs.add(collectionName, doc._id) - await this._publishChildrenOf(doc) - this.subscription.added(collectionName, doc) - } - - // resolve the promise at the end of the added callback - resolve() + const addedPromise = new Promise((resolve, reject) => { + // call the async function to handle the 'added' logic + this._handleAddedAsync(doc, collectionName) + .then(resolve) // resolve the promise at the end of the 'added' callback + .catch(reject) }) // store the promise @@ -75,6 +64,21 @@ class Publication { this._unpublishAllDocuments() } + async _handleAddedAsync(doc, collectionName) { + const alreadyPublished = this.publishedDocs.has(doc._id) + + if (alreadyPublished) { + debugLog('Publication.observeHandle.added', `${collectionName}:${doc._id} already published`) + this.publishedDocs.unflagForRemoval(doc._id) + this._republishChildrenOf(doc) + this.subscription.changed(collectionName, doc._id, doc) + } else { + this.publishedDocs.add(collectionName, doc._id) + await this._publishChildrenOf(doc) + this.subscription.added(collectionName, doc) + } + } + async _republish () { this._stopObservingCursor()