-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdb.js
More file actions
59 lines (53 loc) · 1.81 KB
/
db.js
File metadata and controls
59 lines (53 loc) · 1.81 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
49
50
51
52
53
54
55
56
57
58
59
// DATABASE
const config = require('./config/config.js');
var strings = require("./lang/en.json");
const { Pool, Client, pg, Query } = require('pg');
var client = new Client({
user: config.DB_USER,
host: config.DB_HOST,
database: config.DB_NAME,
password: config.DB_PASS,
port: config.DB_PORT,
ssl: { rejectUnauthorized: false }
});
// Database functions now that all that is declared.
/**
* Run a database query. Renders a 400 error if nothing works. Use with "await".
* @param {object} client The database client credentials. Differs between production and dev.
* @param {string} customQuery The string query with $1, $2, etc.
* @param {array} customValues array of values for $1, $2, etc.
* @param {object} res The ExpressJS API response
* @param {object} req The ExpressJS API request
* @param {boolean} handleZero Determine if we need to handle if the result has 0 rows.
* @returns {array} Array of matching rows to query.
*/
async function query(client, customQuery, customValues, res = null, req = null, handleZero = false) {
try {
const result = await client.query({ text: customQuery, values: customValues });
if (handleZero == true && result.rows.length < 1) {
// We need to handle if the result has no rows. This one has none.
if (res && req) {
return res.status(400).render('pages/400', { session: req.session, code: "Bad Request", cookies: req.cookies });
} else {
return null;
}
}
return result.rows;
} catch (e) {
console.error(e.stack);
if (res && req) {
return res.status(400).render('pages/400', { session: req.session, code: "Bad Request", cookies: req.cookies });
} else {
return null;
}
}
}
client.on('error', (err) => {
console.error('Unexpected error on idle client', err);
});
client.connect();
// MODULE EXPORTS
module.exports = {
query,
client: client
};