UNPKG

2.09 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', 'identity')
57 if (!encoding) this.throw(406, 'supported encodings: gzip, deflate, identity')
58 if (encoding === 'identity') return
59
60 // threshold
61 if (threshold && this.response.length < threshold) return
62
63 // json
64 if (isJSON(body)) {
65 body = JSON.stringify(body, null, this.app.jsonSpaces)
66 }
67
68 this.set('Content-Encoding', encoding)
69 this.res.removeHeader('Content-Length')
70
71 var stream = encodingMethods[encoding](options)
72
73 if (body instanceof Stream) {
74 body.on('error', this.onerror).pipe(stream)
75 } else {
76 stream.end(body)
77 }
78
79 this.body = stream
80 }
81}
82
83/**
84 * Check if `obj` should be interpreted as json.
85 *
86 * TODO: lame... ctx.responseType?
87 */
88
89function isJSON(obj) {
90 if ('string' == typeof obj) return false;
91 if (obj instanceof Stream) return false;
92 if (Buffer.isBuffer(obj)) return false;
93 return true;
94}