import { APIGatewayEvent , Context , Callback , APIGatewayProxyResult } from 'aws-lambda' ; export type Headers = { [ key ] : string ; } ; export type LambdaFunction = ( event : APIGatewayEvent , context ? : Context , callback ? : Callback ) => [ any , number , Headers ] | Promise < [ any , number , Headers ] > ; export type OnSuccesHandler = ( value : any , statusCode : number , headers ? : Headers ) => APIGatewayProxyResult | PromiseLike < APIGatewayProxyResult > ; export type OnErrorHandle = ( error : Error ) => Promise < APIGatewayProxyResult > ; const defaultHeaders = { 'Content-Type' : 'application/json' , 'Access-Control-Allow-Origin' : '*' , 'Access-Control-Allow-Credentials' : true , } ; const onSuccesHandler = ( data , statusCode , headers ? ) : APIGatewayProxyResult | PromiseLike < APIGatewayProxyResult > => ( { statusCode , headers : { ... defaultHeaders , ... headers , } , body : JSON . stringify ( data ) , } ) ; const onErrorHandler = async ( error ) : Promise < APIGatewayProxyResult > => { return { statusCode : 500 , headers : defaultHeaders , body : JSON . stringify ( error ) , } ; } ; export const apiGatewayLambdaWrapper = ( lambda , onSucces = onSuccesHandler , onError = onErrorHandler ) => { return function wrapp ( event , context , callback ) : Promise < APIGatewayProxyResult > { return Promise . resolve ( ) . then ( ( ) => lambda ( event , context , callback ) ) . then ( ( [ res , code , headers ] ) => onSucces ( res , code , headers ) ) . catch ( onError ) ; } ; } ;