add: device db
This commit is contained in:
76
db/device.db.js
Normal file
76
db/device.db.js
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
const pool = require("../config");
|
||||||
|
|
||||||
|
// Get all devices
|
||||||
|
const getAllDevicesDb = async () => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT *
|
||||||
|
FROM m_device
|
||||||
|
WHERE deleted_at IS NULL
|
||||||
|
ORDER BY device_id ASC
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText);
|
||||||
|
return result.recordset;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get device by ID
|
||||||
|
const getDeviceByIdDb = async (id) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT *
|
||||||
|
FROM m_device
|
||||||
|
WHERE device_id = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [id]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get device by device_code
|
||||||
|
const getDeviceByCodeDb = async (code) => {
|
||||||
|
const queryText = `
|
||||||
|
SELECT *
|
||||||
|
FROM m_device
|
||||||
|
WHERE device_code = $1
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
const result = await pool.query(queryText, [code]);
|
||||||
|
return result.recordset[0];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create device
|
||||||
|
const createDeviceDb = async (data) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicInsert("m_device", data);
|
||||||
|
const result = await pool.query(queryText, values);
|
||||||
|
const insertedId = result.recordset[0]?.inserted_id;
|
||||||
|
if (!insertedId) return null;
|
||||||
|
|
||||||
|
return getDeviceByIdDb(insertedId);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Update device
|
||||||
|
const updateDeviceDb = async (id, data) => {
|
||||||
|
const { query: queryText, values } = pool.buildDynamicUpdate("m_device", data, { device_id: id });
|
||||||
|
await pool.query(queryText, values);
|
||||||
|
return getDeviceByIdDb(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Soft delete device
|
||||||
|
const softDeleteDeviceDb = async (id, deletedBy) => {
|
||||||
|
const queryText = `
|
||||||
|
UPDATE m_device
|
||||||
|
SET deleted_at = GETDATE(),
|
||||||
|
deleted_by = $1
|
||||||
|
WHERE device_id = $2
|
||||||
|
AND deleted_at IS NULL
|
||||||
|
`;
|
||||||
|
await pool.query(queryText, [deletedBy, id]);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
getAllDevicesDb,
|
||||||
|
getDeviceByIdDb,
|
||||||
|
getDeviceByCodeDb,
|
||||||
|
createDeviceDb,
|
||||||
|
updateDeviceDb,
|
||||||
|
softDeleteDeviceDb,
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user