-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
55 lines (48 loc) · 1.48 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
54
55
'use strict';
const pg = require('pg');
module.exports = ({ console, config }) => {
const pool = new pg.Pool(config);
return (table) => ({
query(sql, args) {
return pool.query(sql, args);
},
read(id, fields = ['*']) {
const names = fields.join(', ');
const sql = `SELECT ${names} FROM ${table}`;
if (!id) return pool.query(sql);
return pool.query(`${sql} WHERE id = $1`, [id]);
},
async create({ ...record }) {
const keys = Object.keys(record);
const nums = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
nums[i] = `$${++i}`;
}
const fields = '"' + keys.join('", "') + '"';
const params = nums.join(', ');
const sql = `INSERT INTO "${table}" (${fields}) VALUES (${params})`;
return pool.query(sql, data);
},
async update(id, { ...record }) {
const keys = Object.keys(record);
const updates = new Array(keys.length);
const data = new Array(keys.length);
let i = 0;
for (const key of keys) {
data[i] = record[key];
updates[i] = `${key} = $${++i}`;
}
const delta = updates.join(', ');
const sql = `UPDATE ${table} SET ${delta} WHERE id = $${++i}`;
data.push(id);
return pool.query(sql, data);
},
delete(id) {
const sql = 'DELETE FROM ${table} WHERE id = $1';
return pool.query(sql, [id]);
},
});
};