简体   繁体   中英

Manage node-postgres query

I've read through node-postgres's API documentation.

It recommended that we use the pg object to create pooled clients. And in pg.connect api documentation said:

The connect method retrieves a Client from the client pool, or if all pooled clients are busy and the pool is not full, the connect method will create a new client passing its first argument directly to the Client constructor.

So according to the recommendation, does using pg.connect mean "using the pg object to create pooled clients"? If it's not, what does it actually mean?

And in my implementation example, I made several queries in my route:

app.get('/post', function(req, res) {
  pg.connect(dbconfig, function(err, client, done) {
    client.query('SELECT * FROM post', function(err, result) {
      res.render('post/list', { posts: result.rows });
    });
  });
});

app.get('/post/new', function(req, res) {
  res.render('post/new');
});

app.post('/api/v1/post', function(req, res) {
  var b = req.body;
  pg.connect(dbconfig, function(err, client, done) {
    client.query('INSERT INTO post (title, content) VALUES ($1, $2)', 
      [b.title, b.content], 
      function(err, result) {
        done();
        res.redirect('/post');
    });
  });
});

Is it the right way to call pg.connect each time I want to make query? If not, what is the better idea?

It does look, according to the documentation that pg.connect() does handle pooled connections. I would suggest however one thing you could likely do better (assuming you only have one set of credentials your app is using).

If I were looking at doing this, I would work on saving duplication of effort/keystrokes/opportunities for error a bit and look at wrapping pg.connect() in some sort of function you could use that would return client. This would enable you to do something more like:

app.get('/post', function(req, res) {
  db.run( function(client) {
    client.query('SELECT * FROM post', function(err, result) {
      res.render('post/list', { posts: result.rows });
    });
  });
});

However, given the way you have things done, I am not convinced you have a lot to gain by such an approach, so I don't see anything wrong with your approach.

This might be a little outdated now, but take a look at this: https://github.com/aichholzer/Bodega

It will take care of any worries and make your coding experience a little more pleasant. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM