-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.ts
58 lines (41 loc) · 1.36 KB
/
model.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import dbPool from "./db.ts";
import { createInsertValues } from "./utils/index.ts";
class Model {
pool;
table: string;
constructor(table: string) {
this.pool = dbPool
this.table = table
}
async select(columns='*', clause='') {
const client = await this.pool.connect();
let result;
try {
let query = `SELECT ${columns} FROM ${this.table}`;
if (clause) query += ` ${clause}`;
result = await client.queryObject(query);
} finally {
client.release()
}
return result
}
async insert(columns: string, values: (string|number)[][]) {
const client = await this.pool.connect();
const transaction = client.createTransaction(`${this.table}_transact`);
let result;
try {
await transaction.begin();
const _valuesPlaceholder = columns.split(',').map((_t, i) => `$${i+1}`).join(', ')
const query = `INSERT INTO ${this.table}(${columns}) VALUES ${createInsertValues(values)}`;
result = await transaction.queryArray(query);
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
} finally {
client.release()
}
return result
}
}
export default Model