forked from hackforla/tdm-calculator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmssql.js
89 lines (76 loc) · 2.16 KB
/
mssql.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const { Request } = require("tedious");
const ConnectionPool = require("tedious-connection-pool");
const dotenv = require("dotenv");
dotenv.config();
const poolConfig = {
min: 2,
max: 4,
log: false
};
var connectionConfig = {
server: process.env.SQL_SERVER_NAME,
userName: process.env.SQL_USER_NAME,
password: process.env.SQL_PASSWORD,
options: {
database: process.env.SQL_DATABASE_NAME,
instanceName: process.env.SQL_INSTANCE_NAME,
port: process.env.SQL_SERVER_PORT || 1433,
encrypt: process.env.SQL_ENCRYPT
}
};
const pool = new ConnectionPool(poolConfig, connectionConfig);
pool.on("error", err => {
console.error(err);
});
function executeProc(procName, paramsCallback) {
return new Promise((resolve, reject) => {
pool.acquire((err, conn) => {
if (err) {
reject(err);
return;
}
let setIndex = -1;
const response = {};
const request = new Request(procName, err => {
conn.release();
if (err) {
reject(err);
} else {
resolve(response);
}
});
// Get parameters from setParamsCallback callback
if (paramsCallback) {
paramsCallback(request);
}
request.on("row", columns => {
response.resultSets = response.resultSets || [];
response.resultSets[setIndex] = response.resultSets[setIndex] || [];
const row = {};
columns.map((cell, ordinal) => {
if (cell.value === null) {
row[cell.metadata.colName || ordinal] = null;
} else {
row[cell.metadata.colName || ordinal] = cell.value;
}
});
response.resultSets[setIndex].push(row);
});
request.on("returnValue", (paramName, value) => {
response.outputParameters = response.outputParameters || {};
response.outputParameters[paramName] = value;
});
request.on("columnMetadata", function () {
setIndex++;
});
request.on("doneProc", function (rowCount, more, returnStatus) {
response.returnStatus = returnStatus;
});
conn.callProcedure(request);
});
});
}
module.exports = {
pool,
executeProc
};