Skip to content

Instantly share code, notes, and snippets.

@MoritzGruber
Created September 9, 2020 18:38
Show Gist options
  • Save MoritzGruber/fcb75b89e2843c9c03c60bfa800d0f05 to your computer and use it in GitHub Desktop.
Save MoritzGruber/fcb75b89e2843c9c03c60bfa800d0f05 to your computer and use it in GitHub Desktop.
var pg = require('pg');
var shimmer = require('shimmer');
function wrapQuery(orig, name) {
return function wrappedFunction(sql) {
console.time("PSQL: " +sql);
var args = arguments
var index = args.length - 1
var cb = args[index]
if (Array.isArray(cb)) {
index = cb.length - 1
cb = cb[index]
}
if (typeof cb === 'function') {
args[index] = end
return orig.apply(this, arguments)
} else {
cb = null
var query = orig.apply(this, arguments)
if (typeof query.on === 'function') {
query.on('end', end)
query.on('error', end)
} else if (typeof query.then === 'function') {
query.then(end)
}
return query
}
function end() {
console.timeEnd("PSQL: " +sql);
if (cb) return cb.apply(this, arguments)
}
}
}
shimmer.wrap(pg.Client.prototype, 'query', wrapQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment