import { Context , SQSEvent , SQSRecord } from 'aws-lambda' ; import { ProcessMethod } from './EventProcessor' ; export type SqsEvent = SQSEvent ; export interface SqsRoute { source : string | RegExp ; action : ( messages : SQSRecord [ 'body' ] [ ] , context : Context , records : SQSRecord [ ] ) => Promise < any > | any ; } export interface SqsConfig { routes : SqsRoute [ ] ; debug ? : boolean ; } export const process = ( sqsConfig , event , context ) => { if ( sqsConfig . debug ) { console . log ( 'sqs:Event' , JSON . stringify ( event ) ) ; console . log ( 'sqs:context' , context ) ; } if ( ! Array . isArray ( event . Records ) || event . Records . length < 1 || event . Records [ 0 ] . eventSource !== 'aws:sqs' ) { if ( sqsConfig . debug ) { console . log ( 'Event does not look like SQS' ) ; } return null ; } const records = event . Records ; const recordSourceArn = records [ 0 ] . eventSourceARN ; for ( const routeConfig of sqsConfig . routes ) { if ( routeConfig . source instanceof RegExp ) { if ( routeConfig . source . test ( recordSourceArn ) ) { const result = routeConfig . action ( records . map ( record => record . body ) , context , records ) ; return result || { } ; } } else { if ( routeConfig . source === recordSourceArn ) { const result = routeConfig . action ( records . map ( record => record . body ) , context , records ) ; return result || { } ; } } } if ( sqsConfig . debug ) { console . log ( `No source-match for ${ recordSourceArn }` ) ; } return null ; } ;