UNPKG

2 kBJavaScriptView Raw
1/**
2 * Module dependencies.
3 */
4
5var compressible = require('compressible')
6var Stream = require('stream')
7var bytes = require('bytes')
8var zlib = require('zlib')
9
10/**
11 * Encoding methods supported.
12 */
13
14var encodingMethods = {
15 gzip: zlib.createGzip,
16 deflate: zlib.createDeflate
17}
18
19/**
20 * Compress middleware.
21 *
22 * @param {Object} [options]
23 * @return {Function}
24 * @api public
25 */
26
27module.exports = function (options) {
28 options = options || {}
29
30 var filter = options.filter || compressible
31
32 var threshold = !options.threshold ? 1024
33 : typeof options.threshold === 'number' ? options.threshold
34 : typeof options.threshold === 'string' ? bytes(options.threshold)
35 : 1024
36
37 return function* compress(next) {
38 this.vary('Accept-Encoding')
39
40 yield* next
41
42 var body = this.body
43
44 if (this.compress === false
45 || this.method === 'HEAD'
46 || this.status === 204
47 || this.status === 304
48 // Assumes you either always set a body or always don't
49 || body == null
50 ) return
51
52 // forced compression or implied
53 if (!(this.compress === true || filter(this.response.type))) return
54
55 // identity
56 var encoding = this.acceptsEncodings('gzip', 'deflate')
57 if (encoding === 'identity') return
58
59 // threshold
60 if (threshold && this.response.length < threshold) return
61
62 // json
63 if (isJSON(body)) {
64 body = JSON.stringify(body, null, this.app.jsonSpaces)
65 }
66
67 this.set('Content-Encoding', encoding)
68 this.res.removeHeader('Content-Length')
69
70 var stream = encodingMethods[encoding](options)
71
72 if (body instanceof Stream) {
73 body.on('error', this.onerror).pipe(stream)
74 } else {
75 stream.end(body)
76 }
77
78 this.body = stream
79 }
80}
81
82/**
83 * Check if `obj` should be interpreted as json.
84 *
85 * TODO: lame... ctx.responseType?
86 */
87
88function isJSON(obj) {
89 if ('string' == typeof obj) return false;
90 if (obj instanceof Stream) return false;
91 if (Buffer.isBuffer(obj)) return false;
92 return true;
93}