Advertisement
Guest User

Untitled

a guest
May 20th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. const pg = require('pg')
  2.  
  3. // create a config to configure both pooling behavior
  4. // and client options
  5. // note: all config is optional and the environment variables
  6. // will be read if the config is not present
  7. var config = {
  8. user: 'Francesco', // env var: PGUSER
  9. database: 'Francesco', // env var: PGDATABASE
  10. password: '', // env var: PGPASSWORD
  11. host: 'localhost', // Server hosting the postgres database
  12. port: 5432, // env var: PGPORT
  13. max: 10, // max number of clients in the pool
  14. idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed
  15. }
  16.  
  17. const pool = new pg.Pool(config)
  18.  
  19. async function query (q) {
  20. const client = await pool.connect()
  21. let res
  22. try {
  23. await client.query('BEGIN')
  24. try {
  25. res = await client.query(q)
  26. await client.query('COMMIT')
  27. } catch (err) {
  28. await client.query('ROLLBACK')
  29. throw err
  30. }
  31. } finally {
  32. client.release()
  33. }
  34. return res
  35. }
  36.  
  37. async function main () {
  38. try {
  39. const { rows } = await query('SELECT * FROM users')
  40. console.log(JSON.stringify(rows))
  41. } catch (err) {
  42. console.log('Database ' + err)
  43. }
  44. }
  45.  
  46. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement