gzip.js 755 B

12345678910111213141516171819202122232425262728293031323334
  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. //if (isJSON(body)) return;
  18. // 支持 options.threshold
  19. if (options.threshold && ctx.length < options.threshold) return;
  20. if (isJSON(body)) body = JSON.stringify(body);
  21. // 设置 gzip body,修正响应头
  22. const stream = zlib.createGzip();
  23. stream.end(body);
  24. ctx.body = stream;
  25. ctx.set('Content-Encoding', 'gzip');
  26. };
  27. };