UNPKG

men-pack

Version:

men-pack is a collection of funcationalities that can helps developers to easily develop MongoDB Express Node Applications/Backend

66 lines (65 loc) 2.56 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PostgresClient = void 0; const pg_1 = require("pg"); class PostgresClient { constructor() { this.pool = null; } async connect(uri) { this.pool = new pg_1.Pool({ connectionString: uri }); console.log("Connected to PostgreSQL"); } async disconnect() { if (this.pool) { await this.pool.end(); console.log("Disconnected from PostgreSQL"); } } async create(table, data) { if (!this.pool) throw new Error("Database not connected"); const keys = Object.keys(data).join(", "); const values = Object.values(data); const placeholders = values.map((_, index) => `$${index + 1}`).join(", "); const query = `INSERT INTO ${table} (${keys}) VALUES (${placeholders}) RETURNING *`; const result = await this.pool.query(query, values); return result.rows[0]; } async read(table, condition) { if (!this.pool) throw new Error("Database not connected"); const keys = Object.keys(condition) .map((key) => `${key} = $1`) .join(" AND "); const values = Object.values(condition); const query = `SELECT * FROM ${table} WHERE ${keys}`; const result = await this.pool.query(query, values); return result.rows; } async update(table, condition, updates) { if (!this.pool) throw new Error("Database not connected"); const setClause = Object.keys(updates) .map((key, index) => `${key} = $${index + 1}`) .join(", "); const conditionKeys = Object.keys(condition) .map((key, index) => `${key} = $${index + 1 + Object.keys(updates).length}`) .join(" AND "); const query = `UPDATE ${table} SET ${setClause} WHERE ${conditionKeys} RETURNING *`; const values = [...Object.values(updates), ...Object.values(condition)]; const result = await this.pool.query(query, values); return result.rows[0]; } async delete(table, condition) { if (!this.pool) throw new Error("Database not connected"); const keys = Object.keys(condition) .map((key) => `${key} = $1`) .join(" AND "); const values = Object.values(condition); const query = `DELETE FROM ${table} WHERE ${keys}`; await this.pool.query(query, values); } } exports.PostgresClient = PostgresClient;