Files
cod-api/db/brand.db.js
2025-10-10 14:26:12 +07:00

117 lines
3.0 KiB
JavaScript

const pool = require("../config");
// Get all brands
const getAllBrandsDb = async (searchParams = {}) => {
let queryParams = [];
if (searchParams.limit) {
const page = Number(searchParams.page ?? 1) - 1;
queryParams = [Number(searchParams.limit ?? 10), page];
}
const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
["b.brand_name"],
searchParams.criteria,
queryParams
);
queryParams = whereParamOr ? whereParamOr : queryParams;
const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
[
{ column: "b.brand_name", param: searchParams.name, type: "string" },
{ column: "b.created_by", param: searchParams.created_by, type: "number" },
],
queryParams
);
queryParams = whereParamAnd ? whereParamAnd : queryParams;
const queryText = `
SELECT COUNT(*) OVER() AS total_data, b.*
FROM m_brands b
WHERE b.deleted_at IS NULL
${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
${whereOrConditions ? whereOrConditions : ""}
ORDER BY b.brand_id ASC
${searchParams.limit ? `OFFSET $2 ROWS FETCH NEXT $1 ROWS ONLY` : ""};
`;
const result = await pool.query(queryText, queryParams);
const total = result?.recordset.length > 0 ? parseInt(result.recordset[0].total_data, 10) : 0;
return { data: result.recordset, total };
};
// Get brand by ID
const getBrandByIdDb = async (id) => {
const queryText = `
SELECT b.*
FROM m_brands b
WHERE b.brand_id = $1 AND b.deleted_at IS NULL
`;
const result = await pool.query(queryText, [id]);
return result.recordset;
};
// Get brand by name
const getBrandByNameDb = async (name) => {
const queryText = `
SELECT b.*
FROM m_brands b
WHERE b.brand_name = $1 AND b.deleted_at IS NULL
`;
const result = await pool.query(queryText, [name]);
return result.recordset[0];
};
// Create brand
const createBrandDb = async (data) => {
const store = {
...data,
created_at: new Date(),
};
const { query: queryText, values } = pool.buildDynamicInsert("m_brands", store);
const result = await pool.query(queryText, values);
const insertedId = result.recordset[0]?.inserted_id;
return insertedId ? await getBrandByIdDb(insertedId) : null;
};
// Update brand
const updateBrandDb = async (id, data) => {
const store = {
...data,
updated_at: new Date(),
};
const whereData = {
brand_id: id,
};
const { query: queryText, values } = pool.buildDynamicUpdate("m_brands", store, whereData);
await pool.query(`${queryText} AND deleted_at IS NULL`, values);
return getBrandByIdDb(id);
};
// Soft delete brand
const deleteBrandDb = async (id, deletedBy) => {
const queryText = `
UPDATE m_brands
SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
WHERE brand_id = $2 AND deleted_at IS NULL
`;
await pool.query(queryText, [deletedBy, id]);
return true;
};
module.exports = {
getAllBrandsDb,
getBrandByIdDb,
getBrandByNameDb,
createBrandDb,
updateBrandDb,
deleteBrandDb,
};