-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
69 lines (61 loc) · 1.75 KB
/
database.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
66
67
68
69
const { Connection, Request } = require("tedious")
const secrets = require('./secrets.json')
// database config
const config = {
authentication: {
options: {
userName: secrets.username,
password: secrets.password
},
type: "default"
},
server: secrets.server,
options: {
database: secrets.database,
encrypt: true
}
};
const connection = new Connection(config);
function connectDatabase(){
return new Promise((resolve, reject) => {
// Connect to database
connection.on("connect", err => {
if (err) {
console.error(err.message)
reject(err)
}
else {
console.log("Successfully connected to database")
resolve()
}
})
connection.connect();
})
}
function disconnectDatabase(){
connection.close();
}
function queryDatabase(r) {
return new Promise((resolve, reject) => {
console.log(r)
const request = new Request(r, (err, rowCount) => {
if (err) {
console.error(err.message)
}
else {
console.log(`${rowCount} row(s) returned`)
// resolve with rowcount if no json or id response from db
// and use it to determine if the operation was succesful
resolve(rowCount)
}
})
request.on("row", function(columns) {
// db response
let response = columns.map(column => column.value)
console.log(response)
resolve(response)
})
connection.execSql(request)
})
}
module.exports = { queryDatabase, connectDatabase, disconnectDatabase }