generated from li0nhunter/Website-template
Initial commit
This commit is contained in:
141
server/models/db.js
Normal file
141
server/models/db.js
Normal file
@ -0,0 +1,141 @@
|
||||
import dotenv from 'dotenv';
|
||||
import {Pool} from 'pg';
|
||||
dotenv.config();
|
||||
|
||||
const pool = new Pool(process.env.DATABASE_URL ? {connectionString: process.env.DATABASE_URL} : {
|
||||
user: process.env.DB_USER,
|
||||
host: process.env.DB_HOST,
|
||||
database: process.env.DB_NAME,
|
||||
password: process.env.DB_PASSWORD,
|
||||
port: parseInt(process.env.DB_PORT || '5432', 10),
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Generic query function for PostgreSQL database.
|
||||
* @template T
|
||||
* @param {string} text
|
||||
* @param {any[]} [params]
|
||||
* @return {Promise<T[]>}
|
||||
*/
|
||||
async function query(text, params= []) {
|
||||
const start = Date.now();
|
||||
const res = await pool.query(text, params).then(qr => qr);
|
||||
const duration = Date.now() - start;
|
||||
if (params) for (let i = 0; i < params.length; i++) text = text.replace("$".concat(String(i + 1)), params[i]);
|
||||
console.log('executed query', {text, duration, rows: res.rowCount});
|
||||
/**@type T[]*/
|
||||
return res.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* function to insert data into a table.
|
||||
* @template T
|
||||
* @param {string} table The name of the table to insert data into.
|
||||
* @param {Object.<string, any>} map The {keys: values} to insert data into.
|
||||
* @returns {Promise<T[] | Error>} Returns inserted value if the insertion was successful, error otherwise.
|
||||
* */
|
||||
async function insert(table, map) {
|
||||
const valuePlaceholders = Object.keys(map).map((_, index) => `$${index + 1}`).join(", ");
|
||||
const queryText = `INSERT INTO ${table} (${Object.keys(map).join(", ")}) VALUES (${valuePlaceholders}) RETURNING *`;
|
||||
return await query(queryText, Object.values(map))
|
||||
.then(resRows => {
|
||||
if (resRows.length === 0) {
|
||||
console.error('Insert failed: No rows affected');
|
||||
return new Error('Insert failed: No rows affected');
|
||||
}
|
||||
console.log('Insert successful:', resRows);
|
||||
return resRows;
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Insert error:', err);
|
||||
return err;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to update data in a table.
|
||||
* @template T
|
||||
* @param {string} table
|
||||
* @param {Object.<string, any>} updateMap The {keys: values} to update.
|
||||
* @param {Object.<string, any>} conditions The conditions to match to update.
|
||||
* @returns {Promise<T[] | Error>} Returns updated rows if the insertion was successful, error otherwise.
|
||||
*/
|
||||
async function update(table, updateMap, conditions) {
|
||||
if (Object.keys(updateMap).length === 0) {
|
||||
console.error('Update failed: No fields to update');
|
||||
return new Error('Update failed: No fields to update');
|
||||
}
|
||||
if (Object.keys(conditions).length === 0) {
|
||||
console.error('Update failed: No conditions specified');
|
||||
return new Error('Update failed: No conditions specified');
|
||||
}
|
||||
const setClause = Object.keys(updateMap).map((key, index) => `${key} = ${index + 1}`).join(', ');
|
||||
const whereClause = Object.entries(conditions).map(([key, value]) => `${key} = ${value}`).join(' AND ');
|
||||
return await query(`UPDATE ${table} SET ${setClause} WHERE ${whereClause} RETURNING *`, Object.values(updateMap))
|
||||
.then(resRows => {
|
||||
if (resRows.length === 0) {
|
||||
console.error('Update failed: No rows affected');
|
||||
return new Error('Update failed: No rows affected');
|
||||
}
|
||||
console.log('Update successful:', resRows);
|
||||
return resRows;
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Update error:', err);
|
||||
return err;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to delete a row from a table by ID.
|
||||
* @template T
|
||||
* @param {string} table The name of the table to delete from.
|
||||
* @param {Object.<string, any>} conditions The conditions to match to delete row/rows.
|
||||
* @return {Promise<T[] | Error>} Returns true if the deletion was successful, false otherwise.
|
||||
*/
|
||||
async function remove(table, conditions = {}) {
|
||||
if (!conditions || Object.keys(conditions).length === 0) {
|
||||
console.error('Delete failed: No identifier specified');
|
||||
return new Error('Delete failed: No identifier specified');
|
||||
}
|
||||
const whereClause = Object.entries(conditions).map(([key, _], index) => `${key} = ${index + 1}`).join(' AND ');
|
||||
const queryText = `DELETE FROM ${table} WHERE ${whereClause} RETURNING *`;
|
||||
return await query(queryText, Object.values(conditions))
|
||||
.then(resRows => {
|
||||
if (resRows.length === 0) {
|
||||
console.error('Delete failed: No rows affected');
|
||||
return new Error('Delete failed: No rows affected');
|
||||
}
|
||||
console.log('Delete successful:', resRows);
|
||||
return resRows;
|
||||
})
|
||||
.catch(err => {
|
||||
console.error('Delete error:', err);
|
||||
return err;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to get rows from a table based on conditions.
|
||||
* @template T
|
||||
* @param {string} table The name of the table to query.
|
||||
* @param {{}} conditions The conditions to match rows.
|
||||
* @return {Promise<T[]>} Returns an array of rows that match the conditions.
|
||||
*/
|
||||
async function get(table, conditions = {}) {
|
||||
if (Object.keys(conditions).length === 0) {
|
||||
return await query(`SELECT * FROM "${table}"`);
|
||||
}
|
||||
const whereClause = Object.entries(conditions).map(([key, _], index) => `${key} = $${index + 1}`).join(' AND ');
|
||||
return await query(`SELECT * FROM ${table} WHERE ${whereClause}`, Object.values(conditions));
|
||||
}
|
||||
|
||||
export default {
|
||||
pool,
|
||||
query,
|
||||
insert,
|
||||
update,
|
||||
remove,
|
||||
get,
|
||||
};
|
||||
Reference in New Issue
Block a user