Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async function func (name, param) {
- let client = null
- let result = null
- if (!/^\w+$/.test(name)) {
- return new Error('Invalid pg function name')
- }
- try {
- client = await pool.connect()
- } catch (err) {
- return err
- }
- try {
- await client.query('BEGIN')
- const queryResult = await client.query({
- text: `SELECT ${name}(${param.map((_, i) => '$' + (i + 1)).join(',')})`,
- values: param,
- rowMode: 'array'
- })
- const fetchResults = await Promise.all(
- queryResult.rows[0].map(cursor =>
- client.query(`FETCH ALL IN "${cursor}"`)
- )
- )
- const resultRows = fetchResults.map(fetched => {
- return fetched.rows.map(row => {
- Object.keys(row).forEach(col => {
- if (row[col] === null) {
- row[col] = ''
- }
- })
- return row
- })
- })
- result = resultRows.length === 1 ? resultRows[0] : resultRows
- await client.query('COMMIT')
- } catch (err) {
- await client.query('ROLLBACK')
- result = err
- } finally {
- client.release()
- }
- return result
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement