Advertisement
Guest User

Untitled

a guest
Nov 15th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. async function func (name, param) {
  2.   let client = null
  3.   let result = null
  4.  
  5.   if (!/^\w+$/.test(name)) {
  6.     return new Error('Invalid pg function name')
  7.   }
  8.  
  9.   try {
  10.     client = await pool.connect()
  11.   } catch (err) {
  12.     return err
  13.   }
  14.  
  15.   try {
  16.     await client.query('BEGIN')
  17.  
  18.     const queryResult = await client.query({
  19.       text: `SELECT ${name}(${param.map((_, i) => '$' + (i + 1)).join(',')})`,
  20.       values: param,
  21.       rowMode: 'array'
  22.     })
  23.     const fetchResults = await Promise.all(
  24.       queryResult.rows[0].map(cursor =>
  25.         client.query(`FETCH ALL IN "${cursor}"`)
  26.       )
  27.     )
  28.     const resultRows = fetchResults.map(fetched => {
  29.       return fetched.rows.map(row => {
  30.         Object.keys(row).forEach(col => {
  31.           if (row[col] === null) {
  32.             row[col] = ''
  33.           }
  34.         })
  35.         return row
  36.       })
  37.     })
  38.     result = resultRows.length === 1 ? resultRows[0] : resultRows
  39.  
  40.     await client.query('COMMIT')
  41.   } catch (err) {
  42.     await client.query('ROLLBACK')
  43.     result = err
  44.   } finally {
  45.     client.release()
  46.   }
  47.  
  48.   return result
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement