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

后端 未结 7 1670
隐瞒了意图╮
隐瞒了意图╮ 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:42

    I was interested in a very simple handler for this so I made my own without making it over complicated. I'm under no illusions that it's super basic but it could help some people get started. Basically, it connects, runs queries and handles errors for you.

    function runQuery(queryString, callback) {
      // connect to postgres database
      pg.connect(postgresDatabase.url,function(err,client,done) {
        // if error, stop here
        if (err) {console.error(err); done(); callback(); return;}
        // execute queryString
        client.query(queryString,function(err,result) {
          // if error, stop here
          if (err) {console.error(err+'\nQuery: '+queryString); done(); callback(); return;}
          // callback to close connection
          done();
          // callback with results
          callback(result.rows);
        });
      });
    }
    

    Then you would use by calling it this way:

    runQuery("SELECT * FROM table", function(result) {
      // Whatever you need to do with 'result'
    }
    
    0 讨论(0)
提交回复
热议问题