gzip.js 719 B

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const isJSON = require('koa-is-json');
  10. const zlib = require('zlib');
  11. module.exports = options => {
  12. return async function gzip(ctx, next) {
  13. await next();
  14. // 后续中间件执行完成后将响应体转换成 gzip
  15. let body = ctx.body;
  16. if (!body) return;
  17. // 支持 options.threshold
  18. if (options.threshold && ctx.length < options.threshold) return;
  19. if (isJSON(body)) body = JSON.stringify(body);
  20. // 设置 gzip body,修正响应头
  21. const stream = zlib.createGzip();
  22. stream.end(body);
  23. ctx.body = stream;
  24. ctx.set('Content-Encoding', 'gzip');
  25. };
  26. };