Friday, 5 May 2017

When i should use batch and finally to close client connection in pg-promise?

I have a prompt question: When i should use batch and finally to close client connection in pg-promise? This is because I see in official API (http://vitaly-t.github.io/pg-promise/Database.html) that sometimes they use it for select queries, and others not. What would be the best way to performance my db transactions if my db is in the cloud? I use Postgresql 9.5, next are some examples:

db.tx(t => {
    return t.map('SELECT * FROM users WHERE email = $1 LIMIT 1', [data.email], result => {
      return result
    })
  })
  .then(data => {
    // Success
    let user = data[0]
    return res.json({exist: !!user, user})
  })
  .catch(e => {
    console.error('Error select user', e);
    return res.status(500).json({success: false, data: e})
  })
  .finally(pgp.end)

db.tx(t => {
    let query = // some json_build_object query

    return t.map(query, [], categories => categories.json)
  })
  .then(data => {
    return res.json(data)
  })
  .catch(e => {
    console.error('Error select categories', e);
    return res.status(500).json({success: false, data: e})
  })
  .finally(pgp.end)

Thanks for your answers, and additional tips for improve this.



via Daniel Hernández

No comments:

Post a Comment