forked from rauchg/node.dbslayer.js
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdbslayer.js
76 lines (68 loc) · 1.92 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
---
name: dbslayer.js
description: Interface to DBSlayer for Node.JS
author: [Guillermo Rauch](http://devthought.com)
updated: Andy Schuler (andy at leftshoedevevelopment dot com)
...
*/
var sys = require('sys');
var http = require('http');
var events = require('events');
var booleanCommands = ['STAT', 'CLIENT_INFO', 'HOST_INFO', 'SERVER_VERSION', 'CLIENT_VERSION'];
var 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 e = new events.EventEmitter();
var connection = http.createClient(this.port, this.host);
var request = connection.request("GET",'/db?' + escape(JSON.stringify(object)), {'host': this.host});
request.addListener('response',
function(response) {
var data = [];
response.addListener('data',
function(chunk) {
data.push(chunk);
}
);
response.addListener('end',
function() {
try {
var object = JSON.parse(data.join(''));
}
catch(err) {
e.emit('error',err);
return;
}
if (object.MYSQL_ERROR !== undefined){
e.emit('error', object.MYSQL_ERROR, object.MYSQL_ERRNO);
return;
}
if (object.ERROR !== undefined){
e.emit('error', object.ERROR);
return;
}
e.emit('success',key ? object[key] : object);
}
);
}
);
request.end();
return e;
}
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]);
}