Add usage of koa-convert for legacy middleware

closes #565
closes #538
master
blaz 2015-10-29 18:25:46 +01:00 committed by Jonathan Ong
parent eb03d9f61e
commit 3560651bbc
3 changed files with 10 additions and 7 deletions

View File

@ -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);

View File

@ -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;
}

View File

@ -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(/.+/);
});
});