Skip to content

Commit 00bd82b

Browse files
committed
feat(database): implement DatabaseService class for database operations
- Add a `DatabaseService` class to manage database interactions using `pg`'s `PoolClient`. - Implement a `query` method to execute raw SQL queries with parameters. - Add an `insert` method for creating new records, with support for specifying columns to return. - Add an `update` method to modify existing records, with customizable return columns. - Add a `delete` method to remove records, optionally returning the deleted rows. This provides a reusable and structured way to perform database operations with enhanced maintainability and type safety.
1 parent 3dbf777 commit 00bd82b

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

src/database/service/Databas.ts

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { PoolClient, QueryResult, QueryResultRow } from 'pg';
2+
3+
export class DatabaseService {
4+
constructor(private _client: PoolClient) {}
5+
6+
/**
7+
* Runs a query with parameters and returns the result.
8+
*/
9+
async query<T extends QueryResultRow>(sql: string, params: any[] = []): Promise<QueryResult<T>> {
10+
try {
11+
return await this._client.query<T>(sql, params);
12+
} catch (error) {
13+
console.error('Database query error:', error);
14+
throw error;
15+
}
16+
}
17+
18+
/**
19+
* Inserts a new record and returns the inserted row.
20+
*/
21+
async insert<T extends QueryResultRow>(tableName: string, data: Record<string, any>, returning: string[] = ['*']): Promise<T> {
22+
const columns = Object.keys(data).join(', ');
23+
const values = Object.values(data);
24+
const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
25+
const sql = `INSERT INTO "${tableName}" (${columns}) VALUES (${placeholders}) RETURNING ${returning.join(', ')};`;
26+
27+
const result = await this.query<T>(sql, values);
28+
return result.rows[0];
29+
}
30+
31+
/**
32+
* Updates a record and returns the updated row.
33+
*/
34+
async update<T extends QueryResultRow>(tableName: string, data: Record<string, any>, condition: Record<string, any>, returning: string[] = ['*']): Promise<T> {
35+
const setClauses = Object.keys(data)
36+
.map((key, i) => `"${key}" = $${i + 1}`)
37+
.join(', ');
38+
const whereClauses = Object.keys(condition)
39+
.map((key, i) => `"${key}" = $${i + Object.keys(data).length + 1}`)
40+
.join(' AND ');
41+
42+
const values = [...Object.values(data), ...Object.values(condition)];
43+
const sql = `UPDATE "${tableName}" SET ${setClauses} WHERE ${whereClauses} RETURNING ${returning.join(', ')};`;
44+
const result = await this.query<T>(sql, values);
45+
return result.rows[0];
46+
}
47+
48+
/**
49+
* Deletes records and optionally returns the deleted rows.
50+
*/
51+
async delete<T extends QueryResultRow>(tableName: string, condition: Record<string, any>, returning: string[] = ['*']): Promise<T[]> {
52+
const whereClauses = Object.keys(condition)
53+
.map((key, i) => `"${key}" = $${i + 1}`)
54+
.join(' AND ');
55+
const values = Object.values(condition);
56+
const sql = `DELETE FROM "${tableName}" WHERE ${whereClauses} RETURNING ${returning.join(', ')};`;
57+
const result = await this.query<T>(sql, values);
58+
return result.rows;
59+
}
60+
}

0 commit comments

Comments
 (0)