What is the proper way to use the node.js postgresql module?

后端 未结 7 1865
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 01:15

I am writing a node.js app on Heroku and using the pg module. I can\'t figure out the \"right\" way to get a client object for each request that I need to query the database

7条回答
  •  星月不相逢
    2020-11-28 01:31

    Here's how I do it, sort of an "all of the above approach"

    Promise = require 'bluebird'
    pg = module.exports = require 'pg'
    
    Promise.promisifyAll pg.Client.prototype
    Promise.promisifyAll pg.Client
    Promise.promisifyAll pg.Connection.prototype
    Promise.promisifyAll pg.Connection
    Promise.promisifyAll pg.Query.prototype
    Promise.promisifyAll pg.Query
    Promise.promisifyAll pg
    
    connectionString = process.env.DATABASE_URL
    
    module.exports.queryAsync = (sql, values) ->
      pg.connectAsync connectionString
      .spread (connection, release) ->
        connection.queryAsync sql, values
        .then (result) ->
          console.log result.rows[0]
        .finally ->
          release()
    

提交回复
热议问题