Last active
December 15, 2020 01:24
-
-
Save parkan/f0b95f343e18aaadd1bb93b4ca67806d to your computer and use it in GitHub Desktop.
Path parser middleware for lambda-middleware
This file contains 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
// 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