Skip to content

Commit

Permalink
Add support for modifying instance methods from PouchDB.prototype
Browse files Browse the repository at this point in the history
  • Loading branch information
geodic committed Sep 19, 2022
1 parent 669e6c8 commit 5f2ceea
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ function installWrappers (base, handlers = {}) {
} else {
base._handlers[method] = [handler]
// create the new wrapped method
base[method] = replacementMethod(base, method)
base[method] = replacementMethod(method)
}
}
}

function replacementMethod (base, method) {
function replacementMethod (method) {
return function (...args) {
function doMethod () {
// remove callback from args list if present
Expand All @@ -41,26 +41,26 @@ function replacementMethod (base, method) {
callback = args.pop()
}
// compose handlers on top of the base method
let prev = base._originals[method].bind(base)
for (const handler of base._handlers[method]) {
prev = handler.bind(base, prev)
let prev = base._originals[method].bind(this)
for (const handler of this._handlers[method]) {
prev = handler.bind(this, prev)
}
// execute wrapped method, nodify result w/ callback
const result = prev(...args)
if (result.then && callback) { nodify(result, callback) }
return result
}
// await pouchdb task queue before calling the method
if (method !== 'changes' && base.taskqueue && !base.taskqueue.isReady) {
if (method !== 'changes' && this.taskqueue && !this.taskqueue.isReady) {
const dbReady = new Promise((resolve, reject) => {
base.taskqueue.addTask((error) => {
this.taskqueue.addTask((error) => {
// istanbul ignore next
if (error) { reject(error) } else { resolve() }
})
})
return dbReady.then(doMethod)
return dbReady.then(doMethod.bind(this))
} else {
return doMethod()
return doMethod.call(this)
}
}
}
Expand Down

0 comments on commit 5f2ceea

Please sign in to comment.