From 2bc3bb73274d95a74cc911b3eb486a4f383405df Mon Sep 17 00:00:00 2001 From: Jonathan Ong Date: Fri, 24 Jan 2014 14:38:40 -0800 Subject: [PATCH] this.respond=false for bypassing koa's response handling closes #198 --- docs/api/context.md | 6 ++++++ lib/application.js | 2 ++ test/application.js | 25 +++++++++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/docs/api/context.md b/docs/api/context.md index 0fb0032..576fdf1 100644 --- a/docs/api/context.md +++ b/docs/api/context.md @@ -102,6 +102,12 @@ throw err; error messages since you do not want to leak failure details. +### ctx.respond + + To bypass Koa's built-in response handling, you may explicitly set `this.respond = false;`. Use this if you want to write to the raw `res` object instead of letting Koa handle the response for you. + + Note that using this is __not__ supported by Koa. This may break intended functionality of Koa middleware and Koa itself. Using this properly is considered a hack and is only a convenience to those wishing to use traditional `fn(req, res)` functions and middleware within Koa. + ## Request aliases The following accessors and alias [Request](request.md) equivalents: diff --git a/lib/application.js b/lib/application.js index 5918241..40790a2 100644 --- a/lib/application.js +++ b/lib/application.js @@ -184,6 +184,8 @@ function *respond(next){ yield *next; + if (false === this.respond) return; + var res = this.res; if (res.headersSent || !res.socket.writable) return; diff --git a/test/application.js b/test/application.js index 1aefe3e..6b81549 100644 --- a/test/application.js +++ b/test/application.js @@ -94,6 +94,31 @@ describe('app.use(fn)', function(){ }) describe('app.respond', function(){ + describe('when this.respond === false', function(){ + it('should bypass app.respond', function(done){ + var app = koa(); + + app.use(function *(){ + this.body = 'Hello'; + this.respond = false; + + var res = this.res; + setImmediate(function () { + res.setHeader('Content-Type', 'text/plain'); + res.end('lol'); + }) + }) + + var server = app.listen(); + + request(server) + .get('/') + .expect(200) + .expect('lol') + .end(done); + }) + }) + describe('when HEAD is used', function(){ it('should not respond with the body', function(done){ var app = koa();