-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.js
76 lines (64 loc) · 2.13 KB
/
db.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
/*global require, module, console*/
(function () {
"use strict";
var http = require("http");
var makeDBRequest = function (options, emitter, event) {
var headers;
// If POST, automatically set Content-Type to "application/json"
if (options.type === "POST") {
headers = {
"Content-Type": "application/json"
};
}
// If headers settings were passed in the options, use those.
headers = options.headers || headers;
var req = http.request({
host: "127.0.0.1",
port: "5984",
method: options.type,
path: options.path,
headers: headers
}, function (res) {
var data = "";
res.setEncoding("utf8");
res.on("data", function (chunk) {
data += chunk;
});
res.on("end", function () {
var parsed;
try {
parsed = JSON.parse(data);
}
catch (e) {
console.log("ERROR: " + e);
}
emitter.emit(event, parsed);
});
});
// Handle request error (log and fire 'error' event).
req.on('error', function(e) {
console.log("ERROR: " + e.message);
emitter.emit("error", e.message);
});
// If there's data going to the server, stringify it and send.
if (options.data) {
req.write(JSON.stringify(options.data));
}
req.end();
};
var db = {};
db.request = makeDBRequest;
db.post = function (options, emitter, event) {
// Set request type to POST.
options.type = "POST";
makeDBRequest(options, emitter, event);
};
db.get = function (options, emitter, event) {
// Set request type to GET.
options.type = "GET";
// Remove, if present, data to be sent to the server.
delete options.data;
makeDBRequest(options, emitter, event);
};
module.exports = db;
})();