Permalink
Browse files

add detach() method

  • Loading branch information...
1 parent 4daa6af commit bea6f14efa01c8a0e9fe5d05540206d6054eb5c5 Carlos Rodriguez committed Oct 25, 2012
Showing with 44 additions and 6 deletions.
  1. +2 −1 index.js
  2. +1 −0 lib/attach.js
  3. +11 −0 lib/detach.js
  4. +9 −2 lib/middler.js
  5. +21 −3 test/attach.js
View
@@ -7,4 +7,5 @@ exports.parseUrl = require('./lib/parseUrl');
exports.pathRegExp = require('./lib/pathRegExp');
exports.Item = require('./lib/item');
exports.Middler = require('./lib/middler');
-exports.attach = require('./lib/attach');
+exports.attach = require('./lib/attach');
+exports.detach = require('./lib/detach');
View
@@ -8,6 +8,7 @@ module.exports = function attach (server, fn) {
else {
server._middler = new Middler();
}
+ server._middler.server = server;
server._middler._listeners = server.listeners('request').slice(0);
if (server._middler._listeners.length) {
server.removeAllListeners('request');
View
@@ -0,0 +1,11 @@
+var Middler = require('../').Middler;
+
+module.exports = function detach (server, middler) {
+ server.listeners('request').forEach(function (fn) {
+ if (fn._name === 'middlerKernel') {
+ server.removeListener('request', fn);
+ }
+ });
+
+ return middler;
+};
View
@@ -9,6 +9,7 @@ function Middler () {
this.items = [];
this.cache = {};
this.handler = this.handler.bind(this);
+ this.handler._name = 'middlerKernel';
}
inherits(Middler, EventEmitter);
module.exports = Middler;
@@ -21,6 +22,13 @@ Middler.prototype.attach = function (server) {
};
/**
+ * Detaches this instance from a server.
+ */
+Middler.prototype.detach = function () {
+ return require('../').detach(this.server, this);
+};
+
+/**
* Middleware kernel. Embeddable in other middleware!
*/
Middler.prototype.handler = function middlerKernel (req, res, next) {
@@ -75,8 +83,7 @@ Middler.prototype.handler = function middlerKernel (req, res, next) {
next && next();
}
})();
-}
-module.exports = Middler;
+};
/**
* Adds item(s) onto the stack.
View
@@ -6,9 +6,12 @@ describe('attach', function () {
port = p;
done();
});
- })
- it('can attach existing middler instance', function (done) {
- var instance = middler()
+ });
+
+ var instance;
+
+ it('attach', function (done) {
+ instance = middler()
.add(function (req, res, next) {
res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
res.end('hello world');
@@ -23,6 +26,21 @@ describe('attach', function () {
});
});
+ it('detach', function (done) {
+ server.on('request', function (req, res) {
+ res.writeHead(404, {'Content-Type': 'text/plain'});
+ res.end('detached');
+ });
+ instance.detach();
+
+ request.get('http://localhost:' + port + '/', function (res) {
+ assert.equal(res.statusCode, 404);
+ assert.equal(res.headers['content-type'], 'text/plain');
+ assert.equal(res.text, 'detached');
+ done();
+ });
+ });
+
it('closes the server', function (done) {
server.once('close', done);
server.close();

0 comments on commit bea6f14

Please sign in to comment.