Files
SkyArtShop/backend/utils/queryHelpers.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

2025-12-19 20:44:46 -06:00
const { query } = require("../config/database");
const buildSelectQuery = (
table,
conditions = [],
orderBy = "createdat DESC"
) => {
const whereClause =
conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
return `SELECT * FROM ${table} ${whereClause} ORDER BY ${orderBy}`;
};
const getById = async (table, id) => {
const result = await query(`SELECT * FROM ${table} WHERE id = $1`, [id]);
return result.rows[0] || null;
};
const getAllActive = async (table, orderBy = "createdat DESC") => {
const result = await query(
`SELECT * FROM ${table} WHERE isactive = true ORDER BY ${orderBy}`
);
return result.rows;
};
const deleteById = async (table, id) => {
const result = await query(
`DELETE FROM ${table} WHERE id = $1 RETURNING id`,
[id]
);
return result.rowCount > 0;
};
const countRecords = async (table, condition = "") => {
const whereClause = condition ? `WHERE ${condition}` : "";
const result = await query(`SELECT COUNT(*) FROM ${table} ${whereClause}`);
return parseInt(result.rows[0].count);
};
module.exports = {
buildSelectQuery,
getById,
getAllActive,
deleteById,
countRecords,
};