-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBaseDAO.js
65 lines (53 loc) · 1.48 KB
/
BaseDAO.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
56
57
58
59
60
61
62
63
64
65
const { Client } = require('pg');
const named = require('node-postgres-named');
const pool = {
connectionString: process.env.DATABASE_URL
};
export default class BaseDAO {
constructor() {
this.clean();
}
clean() {
this.notEmptyProp = false;
}
beforeResolve(fn, d) {
this.clean();
return fn(d);
}
beforeReject(fn, d) {
// eslint-disable-next-line no-console
console.error(d);
this.clean();
return fn(d);
}
exec(sql, params) {
const self = this;
return new Promise((resolve, reject) => {
const client = new Client(pool);
named.patch(client);
client.connect();
client.query(sql, params, (err, res) => {
client.end();
if (err) return self.beforeReject(reject, err);
if (self.notEmptyProp) {
return res.rowCount === 1 ? self.beforeResolve(resolve, res.rows[0])
: self.beforeReject(reject, res);
}
return self.beforeResolve(resolve, res);
});
});
}
notEmpty() {
this.notEmptyProp = true;
return this;
}
}
export class DAOUtils {
static deleteAllBut(obj, list) {
Object.keys(obj).forEach((key) => {
// eslint-disable-next-line no-param-reassign
if (!list || !list.includes(key)) delete obj[key];
});
return obj;
}
}