Node-postgres Suggested Project Structure - Stack Overflow most recent 30 from stackoverflow.com 2019-10-22T12:41:29Z /feeds/question/57551380 https://creativecommons.org/licenses/by-sa/4.0/rdf /q/57551380 0 Node-postgres Suggested Project Structure Joseph K. /users/6935886 2019-08-19T06:20:31Z 2019-08-19T06:20:31Z <p>I'm trying to understand what is going on behind this <a href="https://node-postgres.com/guides/project-structure" rel="nofollow noreferrer">code</a>:</p> <pre><code>module.exports = { ... getClient: (callback) { pool.connect((err, client, done) =&gt; { const query = client.query.bind(client) // monkey patch the query method to keep track of the last query executed client.query = () =&gt; { 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(() =&gt; { 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) =&gt; { // 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) }) } } </code></pre> <p>Specifically, the <code>monkey patch</code></p> <pre><code>const query = client.query.bind(client) // monkey patch the query method to keep track of the last query executed client.query = () =&gt; { client.lastQuery = arguments client.query.apply(client, arguments) } </code></pre> <p>My thoughts are this</p> <pre><code>const query = client.query.bind(client); // i don't understand this even after reading the mdn doc on bind() client.query = () =&gt; { client.lastQuery = arguments; // assign client.lastQuery function arguments to client.lastQuery object client.query.apply(client, arguments); // i'm not sure } </code></pre> <p>What made it more confusing for me is that I expected to find <code>client.lastQuery</code> in the returned <code>client</code>, but I can't find it in there. However, I can see the <code>query</code> function.</p> <p>Running this code returns at the end</p> <pre><code>A client has been checked out for more than 5 seconds The last executed query on this client was: undefined </code></pre>