Created
March 9, 2023 16:31
-
-
Save domharrington/b7ac7448aa3959b4743d86327cd2f051 to your computer and use it in GitHub Desktop.
Mongoose plugin to add debug() timings to all pre/post middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const debug = require('debug'); | |
function debugMiddlewareTimings(schema) { | |
const vanityNames = { | |
_pres: 'pre', | |
_posts: 'post', | |
}; | |
Object.keys(schema.s.hooks).forEach(hookType => { | |
schema.s.hooks[hookType].forEach((value, key) => { | |
value.forEach((hook, i) => { | |
const { fn } = hook; | |
const _old = fn; | |
const name = fn.name || 'anonymous'; | |
const fnSource = _old.toString(); | |
// This is an internal mongoose middleware | |
if (fnSource.match(/if \(mpath.has\(name, obj\)\)/)) { | |
return; | |
} | |
if (fnSource === 'function() {}') return; | |
const debugKey = `middleware:${vanityNames[hookType]}('${key}', ${name})`; | |
let _new; | |
switch (hook.fn.length) { | |
case 0: | |
_new = function debugOverride() { | |
debug(debugKey); | |
_old.call(this); | |
debug(debugKey); | |
}; | |
break; | |
case 1: | |
_new = function debugOverride(next) { | |
debug(debugKey); | |
_old.call(this, next); | |
debug(debugKey); | |
}; | |
break; | |
case 2: | |
_new = function debugOverride(doc, next) { | |
debug(debugKey); | |
_old.call(this, doc, next); | |
debug(debugKey); | |
}; | |
break; | |
default: | |
throw new Error('Unexpected fn.length in hook'); | |
} | |
// eslint-disable-next-line no-param-reassign | |
schema.s.hooks[hookType].get(key)[i].fn = _new; | |
}); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment