You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
1013 B
JavaScript

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)
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
}
return util.executeQuery({query, returnType, single, tablePrefix})
}