zs-core-db
Version:
Servicios generales de acceso a bases de datos
89 lines (72 loc) • 1.86 kB
JavaScript
const postgres = require("pg");
const CONN = {
__db: null,
};
const timeout = (prom, time) =>
Promise.race([prom, new Promise((_r, rej) => setTimeout(rej, time))]);
const convertParams = (sql, params) => {
const [text, values] = Object.entries(params).reduce(
([sql, array, index], [key, value]) => [
sql.replace(`:${key}`, `$${index}`),
[...array, value],
index + 1,
],
[sql, [], 1]
);
return { text, values };
};
const connect = async (url) => {
const client = new postgres.Client(url);
await timeout(client.connect(), 5000);
const database = url.split("/").reverse()[0];
CONN[database] = client;
use(database);
this.close = close;
this.check = check;
this.use = use;
this.query = query;
this.execute = execute;
this.commit = commit;
return this;
};
const close = async () => CONN.__db.end();
const check = async (url) => {
const database = url.split("/").reverse()[0];
await timeout(CONN[database]?.query("select 1"), 1000);
};
const use = (database) => {
CONN.__db = CONN[database];
return this;
};
const query = async ({
sql = "",
bind = {},
sort = {},
initial = 1,
limit = 0,
options,
}) => {
const minRow = `"__min_row_${new Date().getTime()}"`;
const pagedSQL =
`select mn.* from (\n` +
`select mx.*, rownum ${minRow} from (\n${sql}) mx \n` +
`where rownum <= ${limit <= 0 ? "rownum" : initial + limit - 1}` +
`) mn \nwhere mn.${minRow} >= ${initial}`;
const prepared = convertParams(sql, bind);
const result = (await CONN.__db.query(prepared)).rows;
return result;
};
const execute = async (sql, bind) =>
(await CONN.__db.query(convertParams(sql, bind))).rowCount;
const commit = async (sql, bind) => {
// CONN.__db.commit();
};
module.exports = {
connect,
close,
check,
use,
query,
execute,
commit,
};