2025-12-19 20:44:46 -06:00
|
|
|
const { query } = require("../config/database");
|
|
|
|
|
|
2026-01-04 17:52:37 -06:00
|
|
|
// Whitelist of allowed table names to prevent SQL injection
|
|
|
|
|
const ALLOWED_TABLES = [
|
|
|
|
|
"products",
|
|
|
|
|
"product_images",
|
|
|
|
|
"portfolioprojects",
|
|
|
|
|
"blogposts",
|
|
|
|
|
"pages",
|
|
|
|
|
"adminusers",
|
|
|
|
|
"roles",
|
|
|
|
|
"uploads",
|
|
|
|
|
"media_folders",
|
|
|
|
|
"team_members",
|
|
|
|
|
"site_settings",
|
|
|
|
|
"session",
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
// Validate table name against whitelist
|
|
|
|
|
const validateTableName = (table) => {
|
|
|
|
|
if (!ALLOWED_TABLES.includes(table)) {
|
|
|
|
|
throw new Error(`Invalid table name: ${table}`);
|
|
|
|
|
}
|
|
|
|
|
return table;
|
|
|
|
|
};
|
|
|
|
|
|
2025-12-19 20:44:46 -06:00
|
|
|
const buildSelectQuery = (
|
|
|
|
|
table,
|
|
|
|
|
conditions = [],
|
|
|
|
|
orderBy = "createdat DESC"
|
|
|
|
|
) => {
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName(table);
|
2025-12-19 20:44:46 -06:00
|
|
|
const whereClause =
|
|
|
|
|
conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
|
|
|
return `SELECT * FROM ${table} ${whereClause} ORDER BY ${orderBy}`;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const getById = async (table, id) => {
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName(table);
|
2025-12-19 20:44:46 -06:00
|
|
|
const result = await query(`SELECT * FROM ${table} WHERE id = $1`, [id]);
|
|
|
|
|
return result.rows[0] || null;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const getAllActive = async (table, orderBy = "createdat DESC") => {
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName(table);
|
2025-12-19 20:44:46 -06:00
|
|
|
const result = await query(
|
|
|
|
|
`SELECT * FROM ${table} WHERE isactive = true ORDER BY ${orderBy}`
|
|
|
|
|
);
|
|
|
|
|
return result.rows;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const deleteById = async (table, id) => {
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName(table);
|
2025-12-19 20:44:46 -06:00
|
|
|
const result = await query(
|
|
|
|
|
`DELETE FROM ${table} WHERE id = $1 RETURNING id`,
|
|
|
|
|
[id]
|
|
|
|
|
);
|
|
|
|
|
return result.rowCount > 0;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const countRecords = async (table, condition = "") => {
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName(table);
|
2025-12-19 20:44:46 -06:00
|
|
|
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,
|
2026-01-04 17:52:37 -06:00
|
|
|
validateTableName,
|
2025-12-19 20:44:46 -06:00
|
|
|
};
|