From a471e93977e67c98280af8517100bfe48495bbb2 Mon Sep 17 00:00:00 2001 From: SF-Zhou Date: Thu, 23 Mar 2017 15:50:09 +0800 Subject: [PATCH] docs: fix example code in basics/middleware (#624) --- docs/source/zh-cn/basics/middleware.md | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/source/zh-cn/basics/middleware.md b/docs/source/zh-cn/basics/middleware.md index 97a48d9b20..0940f8359a 100644 --- a/docs/source/zh-cn/basics/middleware.md +++ b/docs/source/zh-cn/basics/middleware.md @@ -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'); } ``` @@ -42,13 +44,13 @@ 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; @@ -56,7 +58,9 @@ module.exports = (options, app) => { 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'); }; }; @@ -106,7 +110,7 @@ module.exports = { module.exports = app => { const gzip = app.middlewares.gzip({ threshold: 1024 }); app.get('/needgzip', gzip, app.controller.handler); -} +}; ``` ## 使用 Koa 的中间件 @@ -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));