Skip to content

Instantly share code, notes, and snippets.

@timoschinkel
Created January 11, 2024 15:51
Show Gist options
  • Save timoschinkel/19ba503fd3037a0d8452f2807e0d7360 to your computer and use it in GitHub Desktop.
Save timoschinkel/19ba503fd3037a0d8452f2807e0d7360 to your computer and use it in GitHub Desktop.
Generalized HTTP handling for TypeScript
/* eslint-disable max-classes-per-file */
/*
* An experiment about how we can structure this codebase
*/
/*
* Request handling infrastructure
*/
import { APIGatewayProxyEvent, APIGatewayProxyHandler, APIGatewayProxyResult } from './Infrastructure/Aws/APIGatewayHandler';
class Request {
public static fromAPIGatewayProxyEvent(event: APIGatewayProxyEvent): Request {
return new Request();
}
}
class Response {
public static fromAPIGatewayProxyResult(result: APIGatewayProxyResult): Response {
return new Response();
}
public toAPIGatewayProxyResult(): APIGatewayProxyResult {
return { statusCode: 500, body: '' };
}
}
type RequestHandler = (request: Request) => Promise<Response>;
class LambdaHandler {
public handle(handler: RequestHandler): APIGatewayProxyHandler {
return (async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> =>
handler(Request.fromAPIGatewayProxyEvent(event))
.then((result) => result.toAPIGatewayProxyResult()));
}
}
/*
* Controllers, defined/constructed in App.ts
*/
class EndpointController {
public async handle(request: Request): Promise<Response> {
console.log('request', request);
return new Response();
}
}
/*
* The actual entry file
*/
const handler = new LambdaHandler(); // we can add middleware if we want
const endpoint = handler.handle(async (request) => new EndpointController().handle(request));
export {
endpoint,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment