index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**!
  2. * koa-gzip - index.js
  3. *
  4. * Copyright(c) 2014
  5. * MIT Licensed
  6. *
  7. * Authors:
  8. * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
  9. */
  10. "use strict";
  11. /**
  12. * Module dependencies.
  13. */
  14. var zlib = require('zlib');
  15. var thunkify = require('thunkify-wrap');
  16. var _gzip = thunkify(zlib.gzip);
  17. module.exports = function (options) {
  18. options = options || {};
  19. // https://developers.google.com/speed/docs/best-practices/payload#GzipCompression
  20. options.minLength = Number(options.minLength) || 150;
  21. return function *gzip(next) {
  22. yield *next;
  23. var body = this.body;
  24. if (200 !== this.status
  25. || !body
  26. || this.acceptsEncodings('gzip') !== 'gzip'
  27. || this.response.header['content-encoding']) {
  28. return;
  29. }
  30. // TODO: Stream body
  31. if ('function' === typeof body.pipe) {
  32. this.set('content-encoding', 'gzip');
  33. this.remove('content-length');
  34. this.body = body.pipe(zlib.createGzip());
  35. return;
  36. }
  37. if (typeof body === 'string') {
  38. body = new Buffer(body);
  39. } else if (!Buffer.isBuffer(body)) {
  40. body = new Buffer(JSON.stringify(body));
  41. }
  42. if (body.length < options.minLength) {
  43. return;
  44. }
  45. var buf = yield _gzip(body);
  46. if (buf.length > body.length) {
  47. return;
  48. }
  49. this.set('content-encoding', 'gzip');
  50. this.body = buf;
  51. };
  52. };