postgres.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. const { Client, Pool } = require( 'pg' ).native;
  2. const cpus = require( 'os' ).cpus().length
  3. let clientOpts = {
  4. host: process.env.DB_HOST || 'localhost',
  5. user: 'benchmarkdbuser',
  6. password: 'benchmarkdbpass',
  7. database: 'hello_world'
  8. };
  9. let pool
  10. const query = async ( text, values ) => ( await pool.query( text, values || undefined ) ).rows;
  11. module.exports = {
  12. async init() {
  13. const client = new Client( clientOpts )
  14. await client.connect()
  15. const res = await client.query( 'SHOW max_connections' )
  16. let maxConnections = Math.floor( res.rows[0].max_connections * 0.9 / cpus )
  17. //1 worker per cpu, each worker pool gets a fraction of the max connections
  18. //only use 90% to avoid too many clients errors
  19. pool = new Pool( Object.assign( { ...clientOpts }, { max: maxConnections } ) )
  20. pool.on( 'error', ( err ) => {
  21. console.error( 'Unexpected client error', err )
  22. } )
  23. await client.end()
  24. },
  25. allFortunes: async () =>
  26. query( 'SELECT * FROM fortune' ),
  27. worldById: async ( id ) =>
  28. query( 'SELECT * FROM world WHERE id = $1', [id] )
  29. .then( arr => arr[0] ),
  30. allWorlds: async () =>
  31. query( 'SELECT * FROM world' ),
  32. bulkUpdateWorld: async worlds => Promise.all(
  33. worlds.map( world =>
  34. query( 'UPDATE world SET randomnumber = $1 WHERE id = $2',
  35. [world.randomnumber, world.id] ) )
  36. ).then( () => worlds )
  37. }