-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
53 lines (47 loc) · 1.04 KB
/
db.js
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
const {Pool} = require('pg');
let pool = undefined;
const {env} = process;
function start() {
if (pool !== undefined) {
throw new Error(`Function 'start' called again without calling function 'end'.`);
}
pool = new Pool({
host: env.PGHOST || 'localhost',
port: env.PGPORT || '6283',
user: env.PGUSER || 'postgres',
password: env.PGPASSWORD || 'postgres',
database: env.PGDATABASE || 'db',
});
}
async function query(text, values) {
let result = await pool.query(text, values);
result = {
rows: result.rows,
rowCount: result.rowCount,
};
return result;
}
async function connect() {
const client = await pool.connect();
return {
release: () => client.release(),
query: async (text, values) => {
let result = await client.query(text, values);
result = {
rows: result.rows,
rowCount: result.rowCount,
};
return result;
},
};
}
async function end() {
await pool.end();
pool = undefined;
}
module.exports = {
start,
query,
connect,
end,
};