import { ProxyIntegrationConfig , ProxyIntegrationEvent } from './lib/proxyIntegration' ; import { SnsConfig , SnsEvent } from './lib/sns' ; import { SqsConfig , SqsEvent } from './lib/sqs' ; import { S3Config , S3Event } from './lib/s3' ; import { Context } from 'aws-lambda' ; import { EventProcessor } from './lib/EventProcessor' ; export interface RouteConfig { proxyIntegration ? : ProxyIntegrationConfig ; sns ? : SnsConfig ; sqs ? : SqsConfig ; s3 ? : S3Config ; debug ? : boolean ; onError ? : ErrorHandler ; } export type ErrorHandler < TContext extends Context = Context > = ( error ? : Error , event ? : RouterEvent , context ? : TContext ) => Promise < any > | any | void ; export type RouterEvent = ProxyIntegrationEvent | SnsEvent | SqsEvent | S3Event ; export const handler = ( routeConfig ) => { const eventProcessorMapping = extractEventProcessorMapping ( routeConfig ) ; return async < TContext extends Context > ( event , context ) => { if ( routeConfig . debug ) { console . log ( 'Lambda invoked with request:' , event ) ; console . log ( 'Lambda invoked with context:' , context ) ; } for ( const [ eventProcessorName , eventProcessor ] of eventProcessorMapping . entries ( ) ) { try { const result = eventProcessor . process ( ( routeConfig as any ) [ eventProcessorName ] , event , context ) ; if ( result ) { return await result ; } else { if ( routeConfig . debug ) { console . log ( 'Event processor couldn\'t handle request.' ) ; } } } catch ( error ) { if ( error . stack ) { console . log ( error . stack ) ; } if ( routeConfig . onError ) { const result = await routeConfig . onError ( error , event , context ) ; if ( result ) { return result ; } } throw error . toString ( ) ; } } throw 'No event processor found to handle this kind of event!' ; } ; } ; const extractEventProcessorMapping = ( routeConfig ) => { const processorMap = new Map < string , EventProcessor > ( ) ; for ( const key of Object . keys ( routeConfig ) ) { if ( key === 'debug' || key === 'onError' ) { continue ; } try { processorMap . set ( key , require ( `./lib/${ key }` ) ) ; } catch ( error ) { throw new Error ( `The event processor '${ key }', that is mentioned in the routerConfig, cannot be instantiated (${ error . toString ( ) })` ) ; } } return processorMap ; } ;