Skip to content

Instantly share code, notes, and snippets.

@parkan
Last active December 15, 2020 01:24
Show Gist options
  • Save parkan/f0b95f343e18aaadd1bb93b4ca67806d to your computer and use it in GitHub Desktop.
Save parkan/f0b95f343e18aaadd1bb93b4ca67806d to your computer and use it in GitHub Desktop.
Path parser middleware for lambda-middleware
// path-parser.ts
import { APIGatewayProxyEvent, APIGatewayProxyResult, Context } from "aws-lambda";
import { Path } from 'path-parser';
type PromiseHandler<TEvent = any, TResult = any> = (
event: TEvent,
context: Context
) => Promise<TResult>;
export const pathParser = (pathExpression: string) =>
<E extends APIGatewayProxyEvent>(handler: PromiseHandler<E, APIGatewayProxyResult>): PromiseHandler<E, APIGatewayProxyResult> =>
async (event: E, context: Context) => {
const path = new Path(pathExpression);
const params = path.test(event.path);
if (params === null) {
throw new Error("path didn't match expectation")
}
event.pathParameters = params;
return handler({ ...event }, context)
}
// handler.ts
import { compose } from "@lambda-middleware/compose";
import { errorHandler } from "@lambda-middleware/http-error-handler";
import { cors } from '@lambda-middleware/cors';
import { pathParser } from './path-parser';
const handlerW = compose(
cors(),
errorHandler(),
pathParser('/path/:pathparam/'),
jsonSerializer(),
// @ts-ignore https://github.com/dbartholomae/lambda-middleware/issues/45
)(handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment