-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbsrc.js
77 lines (60 loc) · 1.74 KB
/
dbsrc.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
// MYSQL connection over Q promise
// Author: Jure Mav
// Date: 2013-05-17
//libraries
var Q = require('q'),
mysql = require('mysql');
// Define our initial class.
var dbSrc = function(conn) {
console.log('aa', conn);
this.initialize(conn);
};
// Initialize: Starts all the fun.
dbSrc.prototype.initialize = function(conn) {
console.log('initialize');
// Q.all([this.connectDb(conn), this.startServer()]).spread(this.ready, this.fail);
this.connectDb(conn).then(this.ready);
};
// Start DB: Initialize DB Connection.
dbSrc.prototype.connectDb = function(conn) {
console.log('connect to DB');
var deferred = Q.defer();
this.pool = mysql.createPool(conn);
deferred.resolve('this.pool');
return deferred.promise;
};
//for pool of connections
dbSrc.prototype.getPoolDb = function() {
console.log('get conn from pool');
var deferred = Q.defer();
this.pool.getConnection(function(err, connection) {
// if(err) console.log('err', err);
if(err) deferred.reject(err);
deferred.resolve(connection);
});
// connection.end();
return deferred.promise;
};
dbSrc.prototype.queryDb = function(queryDB) {
var deferred = Q.defer();
this.getPoolDb()
.then(function(connection) {
console.log('queryDb');
connection.query(queryDB, function(err, rows, fields) {
if(err) deferred.reject(err);
connection.end();
deferred.resolve(rows, fields);
});
});
return deferred.promise;
};
// In case of emergency... RUN IN CIRCLES!
dbSrc.prototype.fail = function(err) {
console.log('fail', err);
};
// Ready: Once bot asynchronous dependencies are ready (MySQL and HTTP)
// do something useful with them.
dbSrc.prototype.ready = function(db, server) {
console.log('mysql connection established & pool ready');
};
exports.dbSrc = dbSrc(conn);