Skip to content

Commit

Permalink
docs: fix example code in basics/middleware (#624)
Browse files Browse the repository at this point in the history
  • Loading branch information
SF-Zhou authored and dead-horse committed Mar 23, 2017
1 parent e87c170 commit a471e93
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions docs/source/zh-cn/basics/middleware.md
Expand Up @@ -17,12 +17,14 @@ function* gzip(next) {
yield next;

// 后续中间件执行完成后将响应体转换成 gzip
const body = this.body;
if!body) return;
let body = this.body;
if (!body) return;
if (isJSON(body)) body = JSON.stringify(body);

// 设置 gzip body,修正响应头
this.body = zlib.createGzip().end(body);
const stream = zlib.createGzip();
stream.end(body);
this.body = stream;
this.set('Content-Encoding', 'gzip');
}
```
Expand All @@ -42,21 +44,23 @@ function* gzip(next) {
const isJSON = require('koa-is-json');
const zlib = require('zlib');

module.exports = (options, app) => {
module.exports = options => {
return function* gzip(next) {
yield next;

// 后续中间件执行完成后将响应体转换成 gzip
const body = this.body;
if!body) return;
let body = this.body;
if (!body) return;

// 支持 options.threshold
if (options.threshold && this.length < options.threshold) return;

if (isJSON(body)) body = JSON.stringify(body);

// 设置 gzip body,修正响应头
this.body = zlib.createGzip().end(body);
const stream = zlib.createGzip();
stream.end(body);
this.body = stream;
this.set('Content-Encoding', 'gzip');
};
};
Expand Down Expand Up @@ -106,7 +110,7 @@ module.exports = {
module.exports = app => {
const gzip = app.middlewares.gzip({ threshold: 1024 });
app.get('/needgzip', gzip, app.controller.handler);
}
};
```

## 使用 Koa 的中间件
Expand All @@ -122,10 +126,10 @@ module.exports = app => {
[koa-compress](https://github.com/koajs/compress) 为例,在 Koa 中使用时:

```js
var koa = require('koa');
var compress = require('koa-compress');
const koa = require('koa');
const compress = require('koa-compress');

var app = koa();
const app = koa();

const options = { threshold: 2048 };
app.use(compress(options));
Expand Down

0 comments on commit a471e93

Please sign in to comment.