-
Notifications
You must be signed in to change notification settings - Fork 0
/
compression.ts
52 lines (45 loc) · 1.43 KB
/
compression.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { IncomingMessage, ServerResponse } from 'http';
import { PassThrough, Transform } from 'stream'
import zlib from 'zlib'
import vary from 'vary'
import { as_nullable_string } from './utils';
const GZIP = 'gzip';
const DEFLATE = 'deflate';
const IDENTITY = 'identity';
export default function compression(
req: IncomingMessage,
res: ServerResponse,
threshhold: number = 1024
): Transform {
const cache_control = as_nullable_string(res.getHeader('Cache-Control'));
if (cache_control && ~cache_control.indexOf('no-transform')) {
return new PassThrough();
}
vary(res, 'Accept-Encoding')
if (req.method !== 'GET') {
return new PassThrough();
}
const content_length = Number(res.getHeader('Content-Length'))
if (isNaN(content_length) || content_length < threshhold) {
return new PassThrough();
}
const accepts = req.headers['accept-encoding']
if (!accepts) {
return new PassThrough();
}
const encoding = as_nullable_string(res.getHeader('Content-Encoding')) ?? IDENTITY;
if (encoding !== IDENTITY || ~accepts.indexOf(IDENTITY)) {
return new PassThrough();
}
if (~accepts.indexOf(GZIP)) {
res.removeHeader('Content-Length')
res.setHeader('Content-Encoding', GZIP)
return zlib.createGzip();
}
if (~accepts.indexOf(DEFLATE)) {
res.removeHeader('Content-Length')
res.setHeader('Content-Encoding', DEFLATE)
return zlib.createDeflate();
}
return new PassThrough();
}