Permalink
Browse files

fix, add test

  • Loading branch information...
1 parent bd6683f commit f1a981ceeb8ba2bc2ebfa5813fcba7dcc9c1ecdd @andrewrk committed Oct 11, 2012
Showing with 65 additions and 7 deletions.
  1. +1 −0 .gitignore
  2. +3 −3 README.md
  3. +3 −2 index.js
  4. +6 −2 package.json
  5. +52 −0 test.js
View
@@ -0,0 +1 @@
+/node_modules
View
@@ -4,12 +4,12 @@ Usage:
```javascript
var sse, express, app;
-sse = require('connect-sse');
+sse = require('connect-sse')();
express = require('express')
app = express()
app.get('/events', sse, function (req, res) {
- req.json("this is an event");
- req.json({here: "is", another: "event");
+ res.json("this is an event");
+ res.json({here: "is", another: "event"});
});
```
View
@@ -1,4 +1,4 @@
-module.exports = function {
+module.exports = function () {
return function sse(req, resp, next){
var message_count;
req.socket.setTimeout(Infinity);
@@ -8,8 +8,9 @@ module.exports = function {
resp.setHeader('Connection', 'keep-alive');
message_count = 0;
resp.json = function(obj){
- resp.write("id: " + message_count++ + "\n");
+ resp.write("id: " + message_count + "\n");
resp.write("data: " + JSON.stringify(obj) + "\n\n");
+ message_count += 1;
};
next();
};
View
@@ -4,7 +4,7 @@
"description": "connect middleware for server sent events (EventSource)",
"main": "index.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "node test.js"
},
"repository": {
"type": "git",
@@ -22,5 +22,9 @@
"events"
],
"author": "Andrew Kelley",
- "license": "BSD"
+ "license": "BSD",
+ "devDependencies": {
+ "eventsource": "0.0.5",
+ "express": "~3.0.0rc5"
+ }
}
View
52 test.js
@@ -0,0 +1,52 @@
+var sse, express, app, EventSource, http, assert;
+
+sse = require('./index')();
+express = require('express');
+EventSource = require('eventsource');
+http = require('http');
+assert = require('assert');
+
+app = express();
+server = http.createServer(app);
+
+app.get('/events', sse, function (req, res) {
+ res.json("this is an event");
+ setTimeout(function() {
+ res.json({here: "is", another: "event"});
+ }, 100);
+});
+
+process.stdout.write("start server...");
+server.listen(0, 'localhost', function() {
+ var expected_messages, url, source;
+
+ console.log("OK");
+ process.stdout.write("checking messages...");
+
+ url = "http://localhost:" + server.address().port + "/events";
+ source = new EventSource(url);
+
+ source.onerror = function(error) {
+ assert(false, error);
+ };
+ message_validators = [
+ function (msg) {
+ assert(msg === "this is an event");
+ },
+ function (msg) {
+ assert(msg.here === "is");
+ assert(msg.another === "event");
+ },
+ ];
+ source.onmessage = function(e) {
+ var validate;
+ validate = message_validators.shift();
+ validate(JSON.parse(e.data));
+ process.stdout.write('.');
+ if (message_validators.length === 0) {
+ console.log("OK");
+ source.close();
+ server.close();
+ }
+ };
+})

0 comments on commit f1a981c

Please sign in to comment.