0

I'm trying to understand what is going on behind this code:

module.exports = {
  ...
  getClient: (callback) {
    pool.connect((err, client, done) => {
      const query = client.query.bind(client)
      // monkey patch the query method to keep track of the last query executed
      client.query = () => {
        client.lastQuery = arguments
        client.query.apply(client, arguments)
      }
      // set a timeout of 5 seconds, after which we will log this client's last query
      const timeout = setTimeout(() => {
        console.error('A client has been checked out for more than 5 seconds!')
        console.error(`The last executed query on this client was: ${client.lastQuery}`)
      }, 5000)
      const release = (err) => {
        // call the actual 'done' method, returning this client to the pool
        done(err)
        // clear our timeout
        clearTimeout(timeout)
        // set the query method back to its old un-monkey-patched version
        client.query = query
      }
      callback(err, client, release)
    })
  }
}

Specifically, the monkey patch

const query = client.query.bind(client)
// monkey patch the query method to keep track of the last query executed
client.query = () => {
    client.lastQuery = arguments
    client.query.apply(client, arguments)
}

My thoughts are this

const query = client.query.bind(client);
// i don't understand this even after reading the mdn doc on bind()

client.query = () => {
    client.lastQuery = arguments;
    // assign client.lastQuery function arguments to client.lastQuery object
    client.query.apply(client, arguments);
    // i'm not sure
}

What made it more confusing for me is that I expected to find client.lastQuery in the returned client, but I can't find it in there. However, I can see the query function.

Running this code returns at the end

A client has been checked out for more than 5 seconds
The last executed query on this client was: undefined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.