-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
48 lines (44 loc) · 1.61 KB
/
db.js
File metadata and controls
48 lines (44 loc) · 1.61 KB
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
var pg, postgres, config;
pg = require("pg");
config = require("./config.js");
module.exports = {
runQuery : function(sql, params, done) {
if (!sql) {
console.error("No query provided");
return done(null);
}
if (!done) { done = function() {}; }
postgres = new pg.Pool({ connectionString : config.DB_CONNECTION_STRING });
postgres.connect(function(err, client, close) {
var i, regex, value;
if (err) {
console.error(JSON.stringify(err));
return done(null);
}
// pg.js parameterisation is too limited - can't use the same parameter in two places
if (params) {
for(i = 0; i < params.length; i++) {
value = params[i];
if (typeof params[i] === "string") {
value = `'${value}'`;
}
if (params[i] == null) {//yes, we want == here incase of null or void 0 etc.
value = "NULL";
}
regex = new RegExp("\\$" + (i+1), "g");
sql = sql.replace(regex, value);
}
}
client.query(sql, [], function(err, result) {
close();
if (err) {
console.log("SQL: " + sql);
console.log("Params: " + JSON.stringify(params));
console.error(JSON.stringify(err));
return done(null);
}
done(result);
});
});
}
};