Skip to content
This repository was archived by the owner on Feb 6, 2024. It is now read-only.

Commit 0d86328

Browse files
committed
Merge branch 'http-emitter' of https://github.com/trotter/cube into 0.2.2
2 parents 279803f + 541ecb1 commit 0d86328

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

lib/cube/emitter-http.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
var util = require("util"),
2+
http = require("http");
3+
4+
module.exports = function(protocol, host, port) {
5+
var emitter = {},
6+
queue = [],
7+
closing;
8+
9+
if (protocol != "http:") throw new Error("invalid HTTP protocol");
10+
11+
function send() {
12+
var events = queue.splice(0, 500);
13+
if (events.length === 0) return;
14+
15+
var body = JSON.stringify(events);
16+
17+
var postOptions = {
18+
host: host,
19+
port: port,
20+
path: "/1.0/event/put",
21+
method: 'POST',
22+
headers: {
23+
'Content-Type': 'application/json',
24+
'Content-Length': body.length
25+
}
26+
};
27+
28+
var postRequest = http.request(postOptions, function(res) {
29+
if (res.statusCode !== 200) queue.unshift.apply(queue, events);
30+
if (queue.length) setTimeout(send, 500);
31+
});
32+
33+
postRequest.on('error', function (e) {
34+
console.warn(e.message);
35+
queue.unshift.apply(queue, events);
36+
});
37+
38+
postRequest.write(body);
39+
postRequest.end();
40+
}
41+
42+
emitter.send = function(event) {
43+
if (!closing && queue.push(event) == 1) process.nextTick(send);
44+
return emitter;
45+
};
46+
47+
emitter.close = function () {
48+
if (queue.length) closing = 1;
49+
return emitter;
50+
};
51+
52+
return emitter;
53+
};

lib/cube/emitter.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
var util = require("util"),
22
url = require("url"),
3+
http = require("./emitter-http"),
34
udp = require("./emitter-udp"),
45
ws = require("./emitter-ws");
56

@@ -9,6 +10,7 @@ module.exports = function(u) {
910
switch (u.protocol) {
1011
case "udp:": emitter = udp; break;
1112
case "ws:": case "wss:": emitter = ws; break;
13+
case "http:": emitter = http; break;
1214
}
1315
return emitter(u.protocol, u.hostname, u.port);
1416
};

0 commit comments

Comments
 (0)