-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsqlConnect.js
More file actions
98 lines (92 loc) · 3.56 KB
/
Copy pathsqlConnect.js
File metadata and controls
98 lines (92 loc) · 3.56 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
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
90
91
92
93
94
95
96
97
98
var sql = require('mssql');
function SqlConnect(config) {
this.configuration = {
user: config.user,
password: config.password,
server: config.server,
port: config.port,
database: config.database,
options: {
encrypt: config.options.encrypt
}
};
}
SqlConnect.prototype.query = function getQueryResult(sqlString) {
var connection = new sql.Connection(this.configuration);
return new Promise(function (fulfill, reject) {
if (connection) {
// try to connect using specified connection
connection.connect().then(function () {
// create a new request
var request = new sql.Request(connection);
request.query(sqlString, function (err, recordset) {
if (err)
reject({
code: err.code,
message: err.message
});
else
fulfill(recordset);
});
}).catch(err => reject({
code: err.code,
message: err.message
}));
}
else
reject('SQL Connection is not available.');
})
}
SqlConnect.prototype.execSP = function getResult(options) {
var connection = new sql.Connection(this.configuration);
return new Promise(function (fulfill, reject) {
if (connection) {
connection.connect().then(function () {
if (!options.hasOwnProperty('sp_name'))
reject('sp_name is missing.');
// create a new request
var request = new sql.Request(connection);
request.multiple = false;
if (options.hasOwnProperty('params')) {
Object.keys(options.params).forEach(function (key) {
var value = options.params[key];
switch (Object.prototype.toString.call(value)) {
case "[object String]":
request.input(key, sql.NVarChar, value);
break;
case "[object Number]":
request.input(key, sql.Int, value);
break;
case "[object Date]":
request.input(key, sql.DateTime, value);
break;
default:
request.input(key, sql.NVarChar, value);
break;
}
})
}
request.execute(options.sp_name, function (err, recordset, returnValue, affected) {
if (err)
reject({
code: err.code,
message: err.message
})
else {
fulfill({
retVal: returnValue,
affected: affected,
data: recordset[0]
})
}
});
}).catch(err => reject({
code: err.code,
message: err.message
}));
}
else
reject('SQL Connection is not available');
});
}
module.exports = SqlConnect;