forked from FGRibreau/node-redis-info
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
103 lines (80 loc) · 2.3 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
var _ = require('lodash');
function Parser(info){
this._info = this._splitStr(info);
Object.defineProperty(this, 'fields', {
get: this.parseFields.bind(this)
});
Object.defineProperty(this, 'databases', {
get: this.parseDatabases.bind(this)
});
}
function startWith(pattern){
return function(value){
return value.indexOf(pattern) === 0;
};
}
function contains(pattern){
return function(value){
return value.indexOf(pattern) !== -1;
};
}
function defstr(v){return v || '';}
function defint(v){return v || 0;}
function apply(func){
return function(v){
return func.apply(this, v);
};
}
function takeN(func, n){return function(v){return func(v[n]);};}
function takeFirst(func){return takeN(func, 0);}
/**
* Split the info string by \n and :
* @param {String} str the returned redis info
* @return {Array} Array of [key, value]
*/
Parser.prototype._splitStr = function(str){
return str.split('\n').map(function(line){return line.trim().split(':');});
};
Parser.prototype.parseDatabases = function(){
if(this._databases){return this._databases;}
return this._databases = this._info.filter(takeFirst(startWith('db'))).map(apply(this._parseDatabaseInfo));
};
Parser.prototype.parseFields = function() {
if(this._fields){return this._fields;}
return this._fields = this._info.reduce(function(m, v){
m[v[0]] = v[1];
return m;
}, {});
};
Parser.prototype._parseDatabaseInfo = function(dbName, value) {
var values = value.split(',');
function extract(param){
return parseInt(defint(defstr(_.detect(values, startWith(param))).split('=')[1]), 10);
}
return {
index : parseInt(dbName.substr(2), 10)
, keys : extract('keys')
, expires: extract('expires')
};
};
/**
* Return all info properties that start with "pattern"
* @param {String} pattern the pattern
* @return {Array} an array of [key, value]
*/
Parser.prototype.startWith = function(pattern){
return this._info.filter(takeFirst(startWith(pattern)));
};
/**
* Return all info properties that contains "pattern"
* @param {String} pattern the pattern
* @return {Array} an array of [key, value]
*/
Parser.prototype.contains = function(pattern){
return this._info.filter(takeFirst(contains(pattern)));
};
module.exports = {
parse: function(info){
return new Parser(info);
}
};