-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathcompression.js
54 lines (47 loc) · 1.31 KB
/
compression.js
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
53
54
'use strict';
/**
* Lightweight web framework for your serverless applications
* @author Jeremy Daly <[email protected]>
* @license MIT
*/
const zlib = require('zlib');
const defaultEnabledEcodings = ['gzip', 'deflate'];
exports.compress = (input, headers, _enabledEncodings) => {
const enabledEncodings = new Set(_enabledEncodings || defaultEnabledEcodings);
const acceptEncodingHeader = headers['accept-encoding'] || '';
const acceptableEncodings = new Set(
acceptEncodingHeader
.toLowerCase()
.split(',')
.map((str) => str.trim())
);
// Handle Brotli compression (Only supported in Node v10 and later)
if (
acceptableEncodings.has('br') &&
enabledEncodings.has('br') &&
typeof zlib.brotliCompressSync === 'function'
) {
return {
data: zlib.brotliCompressSync(input),
contentEncoding: 'br',
};
}
// Handle Gzip compression
if (acceptableEncodings.has('gzip') && enabledEncodings.has('gzip')) {
return {
data: zlib.gzipSync(input),
contentEncoding: 'gzip',
};
}
// Handle deflate compression
if (acceptableEncodings.has('deflate') && enabledEncodings.has('deflate')) {
return {
data: zlib.deflateSync(input),
contentEncoding: 'deflate',
};
}
return {
data: input,
contentEncoding: null,
};
};