代码之家  ›  专栏  ›  技术社区  ›  Joseph K.

节点Postgres建议的项目结构

  •  0
  • Joseph K.  · 技术社区  · 5 年前

    我想知道这背后是怎么回事 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 回复  |  直到 5 年前