import { Context , SNSEvent , SNSMessage , SNSEventRecord } from 'aws-lambda' ; import { ProcessMethod } from './EventProcessor' ; export type SnsEvent = SNSEvent ; export interface SnsRoute { subject : RegExp ; action : ( sns : SNSMessage , context : Context , records : SNSEventRecord [ ] ) => Promise < any > | any ; } export interface SnsConfig { routes : SnsRoute [ ] ; debug ? : boolean ; } export const process = ( snsConfig , event , context ) => { if ( snsConfig . debug ) { console . log ( 'sns:Event' , JSON . stringify ( event ) ) ; console . log ( 'sns:context' , context ) ; } if ( ! Array . isArray ( event . Records ) || event . Records . length < 1 || ! event . Records [ 0 ] . Sns ) { if ( snsConfig . debug ) { console . log ( 'Event does not look like SNS' ) ; } return null ; } const sns = event . Records [ 0 ] . Sns ; for ( const routeConfig of snsConfig . routes ) { if ( routeConfig . subject instanceof RegExp ) { if ( routeConfig . subject . test ( sns . Subject ) ) { const result = routeConfig . action ( sns , context , event . Records ) ; return result || { } ; } } else { console . log ( `SNS-Route with subject-regex '${ routeConfig . subject }' is not a Regex; it is ignored!` ) ; } } if ( snsConfig . debug ) { console . log ( `No subject-match for ${ sns . Subject }` ) ; } return null ; } ;