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, single = false}){ debug(query) const {rows} = await pg.query(query) const mappedObjs = joinjs.map(rows, mappings, returnType + 'Map', returnType + '_') if(single) return mappedObjs[0] return mappedObjs } util.executeFunction = async function({name, params, returnType, single}) { if(!validateFunctionName(name)) throw new Error("Invalid function name: " + name); const query = { text: `select * from sos.${name}( ${getParamString(params.length)} )`, values: params } return util.executeQuery({query, returnType, single}) }