-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (50 loc) · 1.25 KB
/
index.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
'use strict';
const pg = require('pg');
class DB {
static create (arg1, arg2, arg3) {
return new DB(arg1, arg2, arg3);
}
constructor (args, queries, useSpread) {
this.conStr_ = args.conStr;
Object.keys(queries).forEach((name) => {
if(this[name]) {
throw new Error(`Query name collision! The name ${name} is not available.`);
}
var query = queries[name];
if(useSpread) {
this[name] = this.preparedQuerySpread_(query);
} else {
this[name] = this.preparedQuery_(query);
}
});
}
preparedQuery_ (query) {
return (args) => this.query(query, args);
}
preparedQuerySpread_ (query) {
const self = this;
return function () {
const args = Array.prototype.slice.call(arguments);
return self.query(query, args);
};
}
query (query, args) {
return new Promise((resolve, reject) => {
pg.connect(this.conStr_, (err, client, done) => {
if (err) {
done();
return reject(err);
}
client.query(query, args || [], (err2, result) => {
done();
if (err2) {
reject(err2);
} else {
resolve(result);
}
});
});
});
}
}
module.exports = DB;