1 |
|
2 |
|
3 |
|
4 |
|
5 | var compressible = require('compressible')
|
6 | var Stream = require('stream')
|
7 | var bytes = require('bytes')
|
8 | var zlib = require('zlib')
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | var encodingMethods = {
|
15 | gzip: zlib.createGzip,
|
16 | deflate: zlib.createDeflate
|
17 | }
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | module.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 |
|
49 | || body == null
|
50 | ) return
|
51 |
|
52 |
|
53 | if (!(this.compress === true || filter(this.response.type))) return
|
54 |
|
55 |
|
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 |
|
61 | if (threshold && this.response.length < threshold) return
|
62 |
|
63 |
|
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 |
|
85 |
|
86 |
|
87 |
|
88 |
|
89 | function 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 | }
|