-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
106 lines (88 loc) · 2.32 KB
/
index.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
97
98
99
100
101
102
103
104
105
106
"use strict";
var
/*NODE INTERNALS*/
UTIL = require('util'),
EVENTEMITTER = require('events').EventEmitter,
/*NPM THIRD PARTY*/
MYSQL = require('mysql'),
_ = require('lodash');
UTIL.inherits(mysql, EVENTEMITTER);
function mysql(opts){
/*
* opts need to contain
* the connection credentials
*/
var self = this;
EVENTEMITTER.call(self);
//setting the connection credentials
self.host = _.get(opts,'host','');
self.user = _.get(opts,'user','');
self.password = _.get(opts,'password','');
self.db = _.get(opts,'db','');
self.isPaused = false;
self.counter = 1;
self.data = [];
self.connection = MYSQL.createConnection({
host : self.host,
user : self.user,
password : self.password,
database : self.db
});
}//start function
mysql.prototype.establishConnection = function(){
var self = this;
self.connection.connect(function(error){
if(error){
self.emit('connectionError',error);
} else{
self.emit('connectionEstablished',self.connection.threadId);
}
});
};//establish connection using the given credentials
mysql.prototype.setQuery = function(queryString){
var self = this;
self.query = self.connection.query(queryString);
self.query
.on('error',function(error){
self.emit('queryError',error);
})
.on('fields',function(fields){
self.emit('queryFields',fields);
})
.on('result',function(row){
if(self.counter >= self.threshold){
self.pause();
self.data.push(row);
self.emit('queryData',self.data);
} else{
self.counter += 1;
self.data.push(row);
}
})
.on('end',function(){
self.emit('queryEnd',"That's all folks!");
});
};//set the query
mysql.prototype.setThresholdSize = function(size){
var self = this;
self.threshold = size;
};//set threshold size
mysql.prototype.pause = function(){
var self = this;
self.isPaused = true;
self.connection.pause();
};//to pause connection
mysql.prototype.resume = function(){
var self = this;
self.isPaused = false;
self.connection.resume();
};//to resume connection
mysql.prototype.paginate = function(){
var self = this;
if(self.isPaused){
self.counter = 1;
self.data = [];
self.resume();
}
};//to reset counter and paginate
module.exports = mysql;