Last active
April 25, 2020 17:21
-
-
Save joandvgv/9eefe8532cd795569ff54c61c080d0f1 to your computer and use it in GitHub Desktop.
AWS Lambda handler to express
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
import { Request, Response } from "express"; | |
import { Lambdas, LambdaMap } from "./types"; | |
/** | |
* Converts an uri with colon-based parameters to brackets-based parameters | |
* - i.e (:username to {username}) | |
* @param path The url to map | |
*/ | |
const mapPathToApiGateway = (path: string) => path.replace(/:(.+?)\b/g, "{$1}"); | |
const mapExpressRequestToLambdaRequest = (request: Request) => ({ | |
resource: mapPathToApiGateway(request.route.path), | |
pathParameters: request.params, | |
queryStringParameters: request.query, | |
headers: request.headers, | |
body: request.body, | |
httpMethod: request.method | |
}); | |
/** | |
* Calls respective api handler and sends a express response on lambda done callback. | |
* @param request Express request object | |
* @param response Express response object | |
*/ | |
const expressHandler = ( | |
lambda: Lambdas, | |
request: Request, | |
response: Response | |
) => { | |
const map: Partial<LambdaMap> = { | |
users: usersHandler, | |
}; | |
const lambdaRequest = mapExpressRequestToLambdaRequest(request); | |
const lambdaFn = map[lambda]; | |
lambdaFn(lambdaRequest, {}, (error, result) => | |
response | |
.set(result?.headers ?? {}) // sets the express response headers if available | |
.status(result.statusCode) | |
.send(result.body) | |
); | |
}; | |
/** | |
* Calls the express handler with the documents param | |
* - This method is the one used as the `operationId` | |
*/ | |
export const expressUsersHandler = (request: Request, response: Response) => { | |
expressHandler("users", request, response); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment