Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
48 changes: 48 additions & 0 deletions packages/event-handler/src/rest/converters.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { APIGatewayProxyEvent } from 'aws-lambda';

const createBody = (body: string | null, isBase64Encoded: boolean) => {
if (body === null) return null;

if (!isBase64Encoded) {
return body;
}
return Buffer.from(body, 'base64').toString('utf8');
};

export function proxyEventToWebRequest(event: APIGatewayProxyEvent) {
const { httpMethod, path, domainName } = event.requestContext;

const headers = new Headers();
for (const [name, value] of Object.entries(event.headers ?? {})) {
if (value != null) headers.append(name, value);
}

for (const [name, values] of Object.entries(event.multiValueHeaders ?? {})) {
for (const value of values ?? []) {
headers.append(name, value);
}
}
const hostname = headers.get('Host') ?? domainName;
const protocol = headers.get('X-Forwarded-Proto') ?? 'http';

const url = new URL(path, `${protocol}://${hostname}/`);

for (const [name, value] of Object.entries(
event.queryStringParameters ?? {}
)) {
if (value != null) url.searchParams.append(name, value);
}

for (const [name, values] of Object.entries(
event.multiValueQueryStringParameters ?? {}
)) {
for (const value of values ?? []) {
url.searchParams.append(name, value);
}
}
return new Request(url.toString(), {
method: httpMethod,
headers,
body: createBody(event.body, event.isBase64Encoded),
});
}
25 changes: 25 additions & 0 deletions packages/event-handler/src/rest/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isRecord, isString } from '@aws-lambda-powertools/commons/typeutils';
import type { APIGatewayProxyEvent } from 'aws-lambda';
import type { CompiledRoute, Path, ValidationResult } from '../types/rest.js';
import { PARAM_PATTERN, SAFE_CHARS, UNSAFE_CHARS } from './constants.js';

Expand Down Expand Up @@ -43,3 +45,26 @@ export function validatePathPattern(path: Path): ValidationResult {
issues,
};
}

/**
* Type guard to check if the provided event is an API Gateway Proxy event.
*
* We use this function to ensure that the event is an object and has the
* required properties without adding a dependency.
*
* @param event - The incoming event to check
*/
export const isAPIGatewayProxyEvent = (
event: unknown
): event is APIGatewayProxyEvent => {
if (!isRecord(event)) return false;
return (
isString(event.httpMethod) &&
isString(event.path) &&
isString(event.resource) &&
isRecord(event.headers) &&
isRecord(event.requestContext) &&
typeof event.isBase64Encoded === 'boolean' &&
(event.body === null || isString(event.body))
);
};
1 change: 0 additions & 1 deletion packages/event-handler/src/types/rest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ interface CompiledRoute {

type DynamicRoute = Route & CompiledRoute;

// biome-ignore lint/suspicious/noExplicitAny: we want to keep arguments and return types as any to accept any type of function
type RouteHandler<
TParams = Record<string, unknown>,
TReturn = Response | JSONObject,
Expand Down
34 changes: 8 additions & 26 deletions packages/event-handler/tests/unit/rest/BaseRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import type { APIGatewayProxyEvent, Context } from 'aws-lambda';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { BaseRouter } from '../../../src/rest/BaseRouter.js';
import { HttpErrorCodes, HttpVerbs } from '../../../src/rest/constants.js';
import { proxyEventToWebRequest } from '../../../src/rest/converters.js';
import {
BadRequestError,
InternalServerError,
MethodNotAllowedError,
NotFoundError,
} from '../../../src/rest/errors.js';
import { isAPIGatewayProxyEvent } from '../../../src/rest/utils.js';
import type {
HttpMethod,
Path,
Expand Down Expand Up @@ -43,39 +45,19 @@ describe('Class: BaseRouter', () => {
this.logger.error('test error');
}

#isEvent(obj: unknown): asserts obj is APIGatewayProxyEvent {
if (
typeof obj !== 'object' ||
obj === null ||
!('path' in obj) ||
!('httpMethod' in obj) ||
typeof (obj as any).path !== 'string' ||
!(obj as any).path.startsWith('/') ||
typeof (obj as any).httpMethod !== 'string' ||
!Object.values(HttpVerbs).includes(
(obj as any).httpMethod as HttpMethod
)
) {
throw new Error('Invalid event object');
}
}

public async resolve(
event: unknown,
context: Context,
options?: any
): Promise<unknown> {
this.#isEvent(event);
if (!isAPIGatewayProxyEvent(event))
throw new Error('not an API Gateway event!');
const { httpMethod: method, path } = event;
const route = this.routeRegistry.resolve(
method as HttpMethod,
path as Path
);
const request = new Request(`http://localhost${path}`, {
method,
headers: event.headers as Record<string, string>,
body: event.body,
});
const request = proxyEventToWebRequest(event);
try {
if (route == null)
throw new NotFoundError(`Route ${method} ${path} not found`);
Expand Down Expand Up @@ -838,9 +820,9 @@ describe('Class: BaseRouter', () => {
statusCode: HttpErrorCodes.BAD_REQUEST,
error: 'Bad Request',
message: error.message,
hasRequest: options.request instanceof Request,
hasEvent: options.event === testEvent,
hasContext: options.context === context,
hasRequest: options?.request instanceof Request,
hasEvent: options?.event === testEvent,
hasContext: options?.context === context,
}));

app.get('/test', () => {
Expand Down
Loading
Loading