const pg = require('./pg') const mappings = require('./mappings') const joinjs = require('join-js').default; const debug = require('debug')('sos:db') const util = module.exports = {}; const validateFunctionName = name => /^[a-z_]+$/.test(name) const getParamString = (length) => Array.from({length}, (_,i)=>i+1).map(i => '$' + i).join(', ') util.executeQuery = async function({query, returnType, tablePrefix, single = false}){ debug(query) const {rows} = await pg.query(query) if(returnType === 'raw') return rows const mappedObjs = joinjs.map(rows, mappings, returnType + 'Map', tablePrefix || (returnType + '_')) if(single) return mappedObjs[0] return mappedObjs } util.executeFunction = async function({name, params, returnType, single, tablePrefix}) { if(!validateFunctionName(name)) throw new Error("Invalid function name: " + name); const query = { text: `select * from sos.${name}( ${getParamString(params.length)} )`, values: params } const result = await util.executeQuery({query, returnType, single, tablePrefix}) if(returnType === 'raw' && result[0][name] !== undefined) return result[0][name] return result }