-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbQuery.js
More file actions
83 lines (79 loc) · 2.36 KB
/
dbQuery.js
File metadata and controls
83 lines (79 loc) · 2.36 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
const sql = require('mssql')
sql.on('error', err => {
// ... error handler
console.log(err);
})
module.exports = function() {
var connections = [], connected = false, connecting = false
this.request = function (sqlSyntax,connConfig,cb) {
const connection = connWithConfig (connConfig)
if ( connection.connected ) {
getData (sqlSyntax,connection,cb)
} else if ( connection.connecting ) {
setTimeout ( function(){request ( sqlSyntax,connConfig,cb)}, 50 )
} else {
//console.log('new conn')
connect ( connConfig, function (connection,err) {
if (!err) {
request ( sqlSyntax,connConfig,cb)
}
else {
console.log(err)
cb(err);
}
} )
}
}
function connect (connConfig,cb) {
/*
const _connected = connection ? connection._connected : connection
_connecting = connection ? connection._connecting : connection
*/
const connection = connWithConfig (connConfig)
if ( connection.connected ) { cb(connection,false); return }
if ( connection.pool ) { console.log('connection.pool');connection.pool.close() }
connection.connected = false
connection.connecting = true
connection.pool = new sql.ConnectionPool(connConfig, err => {
// ... error checks
if ( err ) {
console.log(err)
cb(false,err);
return;
}
connection.connected = true
connection.connecting = false
cb(connection,false)
})
}
function connWithConfig (connConfig) {
const connFiltered = connections.filter ( connection => connection.config == connConfig )
if ( connFiltered.length ) return connFiltered[0]
const connection = {connected: false,connecting: false, config: connConfig}
connections.push ( connection )
return connections[connections.length-1]
}
function getData (sqlSyntax,connection,cb) {
new sql.Request(connection.pool).query(sqlSyntax, (err, result) => {
//sql.close()
// ... error checks
if ( err ) {
console.log(err)
cb([{Error:err. originalError.info.message,SQL:sqlSyntax}]);
return;
}
//cb([{Error:'err.originalError.info.message',SQL:'sqlSyntax'}]);
cb(result.recordset)
})
// Stored Procedure
/*
new sql.Request()
.input('input_parameter', sql.Int, value)
.output('output_parameter', sql.VarChar(50))
.execute('procedure_name', (err, result) => {
// ... error checks
console.dir(result)
})
*/
}
}