forked from rauchg/node.dbslayer.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbslayer.js
62 lines (50 loc) · 1.61 KB
/
dbslayer.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
/*
---
name: dbslayer.js
description: Interface to DBSlayer for Node.JS
author: [Guillermo Rauch](http://devthought.com)
...
*/
var sys = require('sys'),
http = require('http'),
booleanCommands = ['STAT', 'CLIENT_INFO', 'HOST_INFO', 'SERVER_VERSION', 'CLIENT_VERSION'],
Server = this.Server = function(host, port, timeout){
this.host = host || 'localhost';
this.port = port || 9090;
this.timeout = timeout;
};
Server.prototype.fetch = function(object, key){
var connection = http.createClient(this.port, this.host),
request = connection[connection.get ? 'get' : 'request']('/db?' + escape(JSON.stringify(object)), {'host': this.host}),
promise = new process.Promise();
promise.timeout(this.timeout);
request.finish(function(response){
response.addListener('body', function(data){
try {
var object = JSON.parse(data);
} catch(e){
return promise.emitError(e);
}
if (object.MYSQL_ERROR !== undefined){
promise.emitError(object.MYSQL_ERROR, object.MYSQL_ERRNO);
} else if (object.ERROR !== undefined){
promise.emitError(object.ERROR);
} else {
promise.emitSuccess(key ? object[key] : object);
}
});
});
return promise;
};
Server.prototype.query = function(query){
return this.fetch({SQL: query}, 'RESULT');
};
for (var i = 0, l = booleanCommands.length; i < l; i++){
Server.prototype[booleanCommands[i].toLowerCase()] = (function(command){
return function(){
var obj = {};
obj[command] = true;
return this.fetch(obj, command);
};
})(booleanCommands[i]);
}