Node-postgres建议的项目结构

时间:2019-08-19 06:20:31

标签: node.js postgresql

我正在尝试了解此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)
    })
  }
}

具体来说,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)
}

我的想法是这个

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
}

让我更困惑的是,我期望在返回的client.lastQuery中找到client,但是我找不到它。但是,我可以看到query函数。

运行此代码最后返回

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

0 个答案:

没有答案