From 3560651bbc3a6a026014d9259a8bd4bfb79609df Mon Sep 17 00:00:00 2001 From: blaz Date: Thu, 29 Oct 2015 18:25:46 +0100 Subject: [PATCH] Add usage of koa-convert for legacy middleware closes #565 closes #538 --- Readme.md | 13 ++++++++----- lib/application.js | 2 +- test/application/use.js | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Readme.md b/Readme.md index ccdd77e..773feb5 100644 --- a/Readme.md +++ b/Readme.md @@ -116,25 +116,28 @@ app.use(ctx => { app.listen(3000); ``` -## Example with old version, Koa < 2 +## Example with old signature + +If you want to use old signature or be compatible with old middleware, you must use [koa-convert](https://github.com/gyson/koa-convert) to convert legacy generator middleware to promise middleware. ```js const Koa = require('koa'); const app = new Koa(); +const convert = require('koa-convert') // logger -app.use(function *(next){ +app.use(convert(function *(next){ const start = new Date; yield next; const ms = new Date - start; console.log(`${this.method} ${this.url} - ${ms}`); -}); +})); // response -app.use(function *(){ - this.body = 'Hello World'; +app.use(ctx => { + ctx.body = 'Hello World'; }); app.listen(3000); diff --git a/lib/application.js b/lib/application.js index ed9e231..ee84090 100644 --- a/lib/application.js +++ b/lib/application.js @@ -92,7 +92,7 @@ module.exports = class Application extends Emitter { use(fn) { debug('use %s', fn._name || fn.name || '-'); if (typeof fn !== 'function') throw new TypeError('middleware must be a function!'); - if (isGeneratorFunction(fn)) throw new TypeError('Support for generators has been removed. Use Promises or wrap your generator with co.wrap'); + if (isGeneratorFunction(fn)) throw new TypeError('Support for generators has been removed. See the documentation for examples of how to convert old middleware https://github.com/koajs/koa#example-with-old-signature'); this.middleware.push(fn); return this; } diff --git a/test/application/use.js b/test/application/use.js index bdda573..b04c500 100644 --- a/test/application/use.js +++ b/test/application/use.js @@ -66,6 +66,6 @@ describe('app.use(fn)', function(){ it('should throw error for generator', function(){ const app = new Koa(); - (() => app.use(function *(){})).should.throw('Support for generators has been removed. Use Promises or wrap your generator with co.wrap'); + (() => app.use(function *(){})).should.throw(/.+/); }); });