-
Notifications
You must be signed in to change notification settings - Fork 11
/
mssql.js
96 lines (70 loc) · 2.05 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
90
91
92
93
94
95
96
var sql = Npm.require('mssql');
Sql = {};
Sql.driver = sql;
if (! Meteor.settings.database ||
! Meteor.settings.database.user ||
! Meteor.settings.database.password) {
console.error('mssql: Database unconfigured');
} else {
Sql.connection = new Sql.driver.Connection(Meteor.settings.database, function (err) {
if (err) console.log("Can't connect to database");
});
}
Sql.q = Meteor.wrapAsync(sqlQuery);
function sqlQuery (query, inputs, cb) {
try {
if (typeof inputs === 'function') {
cb = inputs;
inputs = null;
}
var request = new sql.Request(Sql.connection);
if (inputs) {
if (_.isArray(inputs)) {
_.each(inputs, function (e) {
if (e.type) request.input(e.name, e.type, e.value);
else request.input(e.name, e.value);
});
}
else if (_.isObject(inputs)) {
_.each(inputs, function (e, k) {
request.input(k, e);
});
}
}
request.query(query, cb);
}
catch (e) {
return cb(e);
}
}
Sql.ps = Meteor.wrapAsync(prepareStatement);
function prepareStatement (opts, cb) {
opts = opts || {};
opts.inputs = opts.inputs || {};
var request = new sql.PreparedStatement(Sql.connection);
_.each(opts.inputs, function (v, k) {
request.input(k, v);
});
request.prepare(opts.query, function (err, res) {
if (err) return cb(err);
var preparedStatement = Meteor.wrapAsync(request.execute, request);
preparedStatement.unprepare = request.unprepare;
return cb(null, preparedStatement);
});
}
Sql.sp = Meteor.wrapAsync(storedProcedure);
function storedProcedure (opts, cb) {
opts = opts || {};
opts.inputs = opts.inputs || {};
opts.outputs = opts.outputs || {};
var request = new sql.Request(Sql.connection);
_.each(opts.inputs, function (i) {
request.input(i.name, i.type, i.value);
});
_.each(opts.outputs, function (type, name) {
request.output(name, type);
});
request.execute(opts.sp, function(err, recordsets, returnValue) {
return cb(err, recordsets, returnValue)
});
}