|
| 1 | +import type { Middleware } from '../../types/index.js'; |
| 2 | +import type { CompressionOptions } from '../../types/rest.js'; |
| 3 | +import { |
| 4 | + CACHE_CONTROL_NO_TRANSFORM_REGEX, |
| 5 | + COMPRESSION_ENCODING_TYPES, |
| 6 | + DEFAULT_COMPRESSION_RESPONSE_THRESHOLD, |
| 7 | +} from '../constants.js'; |
| 8 | + |
| 9 | +/** |
| 10 | + * Compresses HTTP response bodies using standard compression algorithms. |
| 11 | + * |
| 12 | + * This middleware automatically compresses response bodies when they exceed |
| 13 | + * a specified threshold and the client supports compression. It respects |
| 14 | + * cache-control directives and only compresses appropriate content types. |
| 15 | + * |
| 16 | + * The middleware checks several conditions before compressing: |
| 17 | + * - Response is not already encoded or chunked |
| 18 | + * - Request method is not HEAD |
| 19 | + * - Content length exceeds the threshold |
| 20 | + * - Content type is compressible |
| 21 | + * - Cache-Control header doesn't contain no-transform |
| 22 | + * - Response has a body |
| 23 | + * |
| 24 | + * **Basic compression with default settings** |
| 25 | + * |
| 26 | + * @example |
| 27 | + * ```typescript |
| 28 | + * import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest'; |
| 29 | + * import { compress } from '@aws-lambda-powertools/event-handler/experimental-rest/middleware'; |
| 30 | + * |
| 31 | + * const app = new Router(); |
| 32 | + * |
| 33 | + * app.use(compress()); |
| 34 | + * |
| 35 | + * app.get('/api/data', async () => { |
| 36 | + * return { data: 'large response body...' }; |
| 37 | + * }); |
| 38 | + * ``` |
| 39 | + * |
| 40 | + * **Custom compression settings** |
| 41 | + * |
| 42 | + * @example |
| 43 | + * ```typescript |
| 44 | + * import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest'; |
| 45 | + * import { compress } from '@aws-lambda-powertools/event-handler/experimental-rest/middleware'; |
| 46 | + * |
| 47 | + * const app = new Router(); |
| 48 | + * |
| 49 | + * app.use(compress({ |
| 50 | + * threshold: 2048, |
| 51 | + * encoding: 'deflate' |
| 52 | + * })); |
| 53 | + * |
| 54 | + * app.get('/api/large-data', async () => { |
| 55 | + * return { data: 'very large response...' }; |
| 56 | + * }); |
| 57 | + * ``` |
| 58 | + * |
| 59 | + * @param options - Configuration options for compression behavior |
| 60 | + * @param options.threshold - Minimum response size in bytes to trigger compression (default: 1024) |
| 61 | + * @param options.encoding - Preferred compression encoding to use when client supports multiple formats |
| 62 | + */ |
| 63 | + |
| 64 | +const compress = (options?: CompressionOptions): Middleware => { |
| 65 | + const preferredEncoding = |
| 66 | + options?.encoding ?? COMPRESSION_ENCODING_TYPES.GZIP; |
| 67 | + const threshold = |
| 68 | + options?.threshold ?? DEFAULT_COMPRESSION_RESPONSE_THRESHOLD; |
| 69 | + |
| 70 | + return async (_, reqCtx, next) => { |
| 71 | + await next(); |
| 72 | + |
| 73 | + if ( |
| 74 | + !shouldCompress(reqCtx.request, reqCtx.res, preferredEncoding, threshold) |
| 75 | + ) { |
| 76 | + return; |
| 77 | + } |
| 78 | + |
| 79 | + // Compress the response |
| 80 | + const stream = new CompressionStream(preferredEncoding); |
| 81 | + reqCtx.res = new Response(reqCtx.res.body.pipeThrough(stream), reqCtx.res); |
| 82 | + reqCtx.res.headers.delete('content-length'); |
| 83 | + reqCtx.res.headers.set('content-encoding', preferredEncoding); |
| 84 | + }; |
| 85 | +}; |
| 86 | + |
| 87 | +const shouldCompress = ( |
| 88 | + request: Request, |
| 89 | + response: Response, |
| 90 | + preferredEncoding: NonNullable<CompressionOptions['encoding']>, |
| 91 | + threshold: NonNullable<CompressionOptions['threshold']> |
| 92 | +): response is Response & { body: NonNullable<Response['body']> } => { |
| 93 | + const acceptedEncoding = |
| 94 | + request.headers.get('accept-encoding') ?? COMPRESSION_ENCODING_TYPES.ANY; |
| 95 | + const contentLength = response.headers.get('content-length'); |
| 96 | + const cacheControl = response.headers.get('cache-control'); |
| 97 | + |
| 98 | + const isEncodedOrChunked = |
| 99 | + response.headers.has('content-encoding') || |
| 100 | + response.headers.has('transfer-encoding'); |
| 101 | + |
| 102 | + const shouldEncode = |
| 103 | + !acceptedEncoding.includes(COMPRESSION_ENCODING_TYPES.IDENTITY) && |
| 104 | + (acceptedEncoding.includes(preferredEncoding) || |
| 105 | + acceptedEncoding.includes(COMPRESSION_ENCODING_TYPES.ANY)); |
| 106 | + |
| 107 | + return ( |
| 108 | + shouldEncode && |
| 109 | + !isEncodedOrChunked && |
| 110 | + request.method !== 'HEAD' && |
| 111 | + (!contentLength || Number(contentLength) > threshold) && |
| 112 | + (!cacheControl || !CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl)) && |
| 113 | + response.body !== null |
| 114 | + ); |
| 115 | +}; |
| 116 | + |
| 117 | +export { compress }; |
0 commit comments