@szegedsw/lib-node
Version:
A little framework published by Szeged Software Zrt. in order to enhance api endpoint security and create reuseable code. Email module, Logging system, and much more. Further improvements are expected.
56 lines • 2.32 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.countriesSql = exports.rownumSql = exports.joinSql = exports.whereSql = exports.isWhere = void 0;
const config_1 = require("../config/config");
function isWhere(where, key) {
return (where[key] !== null &&
where[key] !== undefined &&
(typeof where[key] !== "number" || where[key] !== -1) &&
(typeof where[key] !== "string" || where[key].trim() !== ""));
}
exports.isWhere = isWhere;
function whereSql(where, sql, join = false) {
let equalsStr = "";
// const apostrophe = `${join ? "" : "'"}`;
Object.keys(where || {}).forEach((key) => {
if (isWhere(where, key)) {
if (typeof where[key] === "string") {
where[key] = where[key].trim();
}
let equation = `= ${where[key]}`;
if (key.startsWith("%") && key.endsWith("%")) {
equation = `like '%' || ${where[key]} || '%'`;
key = key.substring(1, key.length - 1);
}
equalsStr += `${equalsStr.length > 0 || sql.includes(" WHERE ") ? " AND " : " WHERE "}${key.trim()} ${equation}`;
}
});
return sql.replace(join ? "$JOIN" : "$WHERE", equalsStr);
}
exports.whereSql = whereSql;
function joinSql(join, sql) {
return whereSql(join, sql, true);
}
exports.joinSql = joinSql;
function rownumSql(sql, to) {
if (Number(to) !== -1) {
return `SELECT * FROM (${sql}) ${config_1.env.databaseType === "POSTGRES" ? "as data " : ""}WHERE rownum <= ${to ? Math.min(config_1.env.databaseRownum, to) : config_1.env.databaseRownum}`;
}
return sql;
}
exports.rownumSql = rownumSql;
function countriesSql(countries, sql) {
Object.keys(countries || {}).forEach((key) => {
const country = String(countries[key])
.split(",")
.filter((value) => value.trim().length > 0)
.reduce((previous, current) => `${previous + (previous.length > 0 ? "," : "")}'${current}'`, "");
if (!country) {
throw new Error("no countries");
}
sql = sql.replace("$COUNTRY", `${sql.includes("WHERE") ? " AND " : " WHERE "}${key.trim()} in (${country})`);
});
return sql;
}
exports.countriesSql = countriesSql;
//# sourceMappingURL=sql-handler.js.map