Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/event-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@
"types": "./lib/esm/rest/index.d.ts",
"default": "./lib/esm/rest/index.js"
}
},
"./experimental-rest/middleware": {
"require": {
"types": "./lib/cjs/rest/middleware/index.d.ts",
"default": "./lib/cjs/rest/middleware/index.js"
},
"import": {
"types": "./lib/esm/rest/middleware/index.d.ts",
"default": "./lib/esm/rest/middleware/index.js"
}
}
},
"typesVersions": {
Expand Down
12 changes: 12 additions & 0 deletions packages/event-handler/src/rest/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,15 @@ export const PARAM_PATTERN = /:([a-zA-Z_]\w*)(?=\/|$)/g;
export const SAFE_CHARS = "-._~()'!*:@,;=+&$";

export const UNSAFE_CHARS = '%<> \\[\\]{}|^';

export const DEFAULT_COMPRESSION_RESPONSE_THRESHOLD = 1024;

export const CACHE_CONTROL_NO_TRANSFORM_REGEX =
/(?:^|,)\s*?no-transform\s*?(?:,|$)/i;

export const COMPRESSION_ENCODING_TYPES = {
GZIP: 'gzip',
DEFLATE: 'deflate',
IDENTITY: 'identity',
ANY: '*',
} as const;
30 changes: 27 additions & 3 deletions packages/event-handler/src/rest/converters.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import type { HandlerResponse } from '../types/rest.js';
import type { CompressionOptions, HandlerResponse } from '../types/rest.js';
import { COMPRESSION_ENCODING_TYPES } from './constants.js';
import { isAPIGatewayProxyResult } from './utils.js';

/**
Expand Down Expand Up @@ -89,11 +90,34 @@ export const webResponseToProxyResult = async (
}
}

// Check if response contains compressed/binary content
const contentEncoding = response.headers.get(
'content-encoding'
) as CompressionOptions['encoding'];
let body: string;
let isBase64Encoded = false;

if (
contentEncoding &&
[
COMPRESSION_ENCODING_TYPES.GZIP,
COMPRESSION_ENCODING_TYPES.DEFLATE,
].includes(contentEncoding)
) {
// For compressed content, get as buffer and encode to base64
const buffer = await response.arrayBuffer();
body = Buffer.from(buffer).toString('base64');
isBase64Encoded = true;
} else {
// For text content, use text()
body = await response.text();
}

const result: APIGatewayProxyResult = {
statusCode: response.status,
headers,
body: await response.text(),
isBase64Encoded: false,
body,
isBase64Encoded,
};

if (Object.keys(multiValueHeaders).length > 0) {
Expand Down
117 changes: 117 additions & 0 deletions packages/event-handler/src/rest/middleware/compress.ts
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();

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 };
1 change: 1 addition & 0 deletions packages/event-handler/src/rest/middleware/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { compress } from './compress.js';
6 changes: 6 additions & 0 deletions packages/event-handler/src/types/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ type ValidationResult = {
issues: string[];
};

type CompressionOptions = {
encoding?: 'gzip' | 'deflate';
threshold?: number;
};

export type {
CompiledRoute,
DynamicRoute,
Expand All @@ -131,4 +136,5 @@ export type {
RestRouteHandlerOptions,
RouteRegistryOptions,
ValidationResult,
CompressionOptions,
};
Loading