Initial commit
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
// ROOT/services/logger/readLogs.js
|
||||
|
||||
// Import the MySQL pools from your database service
|
||||
const pools = require('../database/pools').get();
|
||||
|
||||
// Database name used for logging
|
||||
const dbName = 'logging';
|
||||
|
||||
// Use the Read pool with the "system" role
|
||||
const readPool = pools[dbName].r.s;
|
||||
|
||||
/*
|
||||
* Function: getAllLogs
|
||||
* Description: Retrieves all log entries from a specified table.
|
||||
* @param {string} tableName - Name of the table to query.
|
||||
* @returns {Array|Object} - Returns an array of log entries, or an error object.
|
||||
*/
|
||||
async function getAllLogs(tableName) {
|
||||
if (!tableName) throw new Error('Table name is required');
|
||||
|
||||
try {
|
||||
const [rows] = await readPool.query(`SELECT * FROM ${tableName}`);
|
||||
return rows;
|
||||
} catch (err) {
|
||||
console.error('Error reading logs from DB:', err);
|
||||
return { success: false, error: err };
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Function: getLogs
|
||||
* Description: Retrieves log entries from a specified table that match optional filter criteria.
|
||||
* @param {string} tableName - Name of the table to query.
|
||||
* @param {Object} filter - Optional key/value pairs representing column filters.
|
||||
* Example: { user: 'andi', success: true }
|
||||
* @returns {Array|Object} - Returns an array of filtered log entries, or an error object.
|
||||
*/
|
||||
async function getLogs(tableName, filter = {}) {
|
||||
if (!tableName) throw new Error('Table name is required');
|
||||
|
||||
// Start building the SQL query
|
||||
let sql = `SELECT * FROM ${tableName}`;
|
||||
const values = [];
|
||||
|
||||
const filterKeys = Object.keys(filter);
|
||||
if (filterKeys.length > 0) {
|
||||
// Build WHERE clauses dynamically
|
||||
const whereClauses = filterKeys.map(key => {
|
||||
values.push(filter[key]);
|
||||
return `${key} = ?`;
|
||||
});
|
||||
sql += ' WHERE ' + whereClauses.join(' AND ');
|
||||
}
|
||||
|
||||
try {
|
||||
const [rows] = await readPool.query(sql, values);
|
||||
return rows;
|
||||
} catch (err) {
|
||||
console.error('Error reading filtered logs from DB:', err);
|
||||
return { success: false, error: err };
|
||||
}
|
||||
}
|
||||
|
||||
// Export both functions for external use
|
||||
module.exports = {
|
||||
getAll: getAllLogs,
|
||||
get: getLogs
|
||||
};
|
||||
Reference in New Issue
Block a user