generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 175
feat(event-handler): added compress middleware for the REST API event handler #4495
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
d264ab9
Added compress middleware
sdangol 6c477ab
Added tests for the middleware
sdangol aa76a42
added export for middleware
sdangol ea9cc34
fixed tests and improved coverage
sdangol 6670bad
Added docstring comment for the compress function
sdangol aecd5bc
Changed map to foreach
sdangol 3bfccbc
Removed unused imports
sdangol 2627663
Addressed the feedbacks
sdangol 980c4f2
Broke down the regex into chunks and optimized tests
sdangol 67339fb
Broke down the regex further
sdangol 87058a2
Updated the regex
sdangol 4f071ce
Refactored the logic to remove checks for content types
sdangol 558caf5
Added tests for the converter
sdangol b74783e
Removed unused imports and unnecessary assignments
sdangol 70dae88
Simplified the shouldCompress check and added base64encoded checks
sdangol 4458a36
Added check for base64 encoding when the response is compressed
sdangol f24c501
Merge branch 'main' into feat/compress-middleware
sdangol c5270fa
Merge branch 'main' into feat/compress-middleware
svozza f6967a5
Fixed the tests structure
sdangol bc0241c
Merge branch 'feat/compress-middleware' of github.com:aws-powertools/…
sdangol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
import type { Middleware } from '../../types/index.js'; | ||
import type { CompressionOptions } from '../../types/rest.js'; | ||
import { | ||
CACHE_CONTROL_NO_TRANSFORM_REGEX, | ||
COMPRESSION_ENCODING_TYPES, | ||
DEFAULT_COMPRESSION_RESPONSE_THRESHOLD, | ||
} from '../constants.js'; | ||
|
||
/** | ||
* Compresses HTTP response bodies using standard compression algorithms. | ||
* | ||
* This middleware automatically compresses response bodies when they exceed | ||
* a specified threshold and the client supports compression. It respects | ||
* cache-control directives and only compresses appropriate content types. | ||
* | ||
* The middleware checks several conditions before compressing: | ||
* - Response is not already encoded or chunked | ||
* - Request method is not HEAD | ||
* - Content length exceeds the threshold | ||
* - Content type is compressible | ||
* - Cache-Control header doesn't contain no-transform | ||
* - Response has a body | ||
* | ||
* **Basic compression with default settings** | ||
* | ||
* @example | ||
* ```typescript | ||
* import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
* import { compress } from '@aws-lambda-powertools/event-handler/experimental-rest/middleware'; | ||
* | ||
* const app = new Router(); | ||
* | ||
* app.use(compress()); | ||
* | ||
* app.get('/api/data', async () => { | ||
* return { data: 'large response body...' }; | ||
* }); | ||
* ``` | ||
* | ||
* **Custom compression settings** | ||
* | ||
* @example | ||
* ```typescript | ||
* import { Router } from '@aws-lambda-powertools/event-handler/experimental-rest'; | ||
* import { compress } from '@aws-lambda-powertools/event-handler/experimental-rest/middleware'; | ||
* | ||
* const app = new Router(); | ||
* | ||
* app.use(compress({ | ||
* threshold: 2048, | ||
* encoding: 'deflate' | ||
* })); | ||
* | ||
* app.get('/api/large-data', async () => { | ||
* return { data: 'very large response...' }; | ||
* }); | ||
* ``` | ||
* | ||
* @param options - Configuration options for compression behavior | ||
* @param options.threshold - Minimum response size in bytes to trigger compression (default: 1024) | ||
* @param options.encoding - Preferred compression encoding to use when client supports multiple formats | ||
*/ | ||
|
||
const compress = (options?: CompressionOptions): Middleware => { | ||
const preferredEncoding = | ||
options?.encoding ?? COMPRESSION_ENCODING_TYPES.GZIP; | ||
const threshold = | ||
options?.threshold ?? DEFAULT_COMPRESSION_RESPONSE_THRESHOLD; | ||
|
||
return async (_, reqCtx, next) => { | ||
await next(); | ||
sdangol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
if ( | ||
!shouldCompress(reqCtx.request, reqCtx.res, preferredEncoding, threshold) | ||
) { | ||
return; | ||
} | ||
|
||
// Compress the response | ||
const stream = new CompressionStream(preferredEncoding); | ||
reqCtx.res = new Response(reqCtx.res.body.pipeThrough(stream), reqCtx.res); | ||
reqCtx.res.headers.delete('content-length'); | ||
reqCtx.res.headers.set('content-encoding', preferredEncoding); | ||
}; | ||
}; | ||
|
||
const shouldCompress = ( | ||
request: Request, | ||
response: Response, | ||
preferredEncoding: NonNullable<CompressionOptions['encoding']>, | ||
threshold: NonNullable<CompressionOptions['threshold']> | ||
): response is Response & { body: NonNullable<Response['body']> } => { | ||
const acceptedEncoding = | ||
request.headers.get('accept-encoding') ?? COMPRESSION_ENCODING_TYPES.ANY; | ||
const contentLength = response.headers.get('content-length'); | ||
const cacheControl = response.headers.get('cache-control'); | ||
|
||
const isEncodedOrChunked = | ||
response.headers.has('content-encoding') || | ||
response.headers.has('transfer-encoding'); | ||
|
||
const shouldEncode = | ||
!acceptedEncoding.includes(COMPRESSION_ENCODING_TYPES.IDENTITY) && | ||
(acceptedEncoding.includes(preferredEncoding) || | ||
acceptedEncoding.includes(COMPRESSION_ENCODING_TYPES.ANY)); | ||
|
||
return ( | ||
shouldEncode && | ||
!isEncodedOrChunked && | ||
request.method !== 'HEAD' && | ||
(!contentLength || Number(contentLength) > threshold) && | ||
(!cacheControl || !CACHE_CONTROL_NO_TRANSFORM_REGEX.test(cacheControl)) && | ||
response.body !== null | ||
); | ||
}; | ||
|
||
export { compress }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export { compress } from './compress.js'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.