import { APIGatewayProxyEvent , APIGatewayProxyResult } from "aws-lambda" ; import { AWSError } from "aws-sdk" ; import { validate } from "jsonschema" ; import { ErrorResponse } from "../../common" ; template TParameters template TEvent export interface HandlerCallbackEvent < TParameters extends { } , TEvent extends { } > { path : string ; pathParameters : TParameters ; headers : { [ name ] : string | undefined ; } ; body : TEvent ; } template TResponse export interface HandlerCallbackResponse < TResponse > { statusCode ? : number ; headers ? : { [ name ] : string ; } ; body ? : TResponse | ErrorResponse ; } template TParameters template TEvent template TResponse export type HandlerCallback < TParameters extends { } , TEvent extends { } , TResponse = void > = ( event : HandlerCallbackEvent < TParameters , TEvent > ) => Promise < HandlerCallbackResponse < TResponse > | void > ; param err return export function translate ( err ) { switch ( err . code ) { case "SyntaxError" : err . code = "TypeError" ; err . message = "Invalid request" ; return err ; case "UserLambdaValidationException" : err . code = "AliasExistsException" ; err . message = err . message . replace ( "PreSignUp failed with error " , "" ) ; return err ; default : return err ; } } template TParameters template TEvent template TResponse param schema param cb return export function handler < TParameters extends { } , TEvent extends { } , TResponse = void > ( schema , cb ) { return async ( event ) : Promise < APIGatewayProxyResult > => { try { const data = event . httpMethod === "POST" ? JSON . parse ( event . body || "{}" ) : { } ; const result = validate ( data , schema ) ; if ( ! result . valid ) throw new TypeError ( "Invalid request" ) ; const { statusCode , headers , body } = { statusCode : undefined , headers : { } , body : undefined , ... await cb ( { path : event . path , pathParameters : event . pathParameters as TParameters , headers : event . headers , body : data } ) } ; return { statusCode : statusCode || ( body ? 200 : 204 ) , headers , body : body ? JSON . stringify ( body ) : "" } ; } catch ( err ) { err . code = err . code || err . name ; err = translate ( err ) ; return { statusCode : err . statusCode || 400 , body : JSON . stringify ( { type : err . code , message : err . message . replace ( /\.$/ , "" ) } ) } ; } } ; }