import { SNSEvent } from "aws-lambda" ; import { CognitoIdentityServiceProvider , SES } from "aws-sdk" ; import { RegisterMessage , ResetMessage } from "./messages" ; import { VerificationCode } from "./verification" ; param context return function template ( code ) { switch ( code . context ) { case "register" : return new RegisterMessage ( { name : process . env . COGNITO_IDENTITY_POOL_NAME ! , domain : process . env . COGNITO_IDENTITY_POOL_PROVIDER ! , code : code . id } ) ; case "reset" : return new ResetMessage ( { name : process . env . COGNITO_IDENTITY_POOL_NAME ! , domain : process . env . COGNITO_IDENTITY_POOL_PROVIDER ! , code : code . id } ) ; default : throw new Error ( `Invalid verification context: "${ code . context }"` ) ; } } param event return export function handler ( event ) { return event . Records . reduce ( ( promise , record ) => promise . then ( async ( ) => { const code = JSON . parse ( record . Sns . Message ) ; const [ { UserAttributes } , message ] = await Promise . all ( [ new CognitoIdentityServiceProvider ( { apiVersion : "2016-04-18" } ) . adminGetUser ( { UserPoolId : process . env . COGNITO_USER_POOL_ID ! , Username : code . subject } ) . promise ( ) , template ( code ) . compose ( ) ] ) ; const { Value : email } = UserAttributes ! . find ( attr => { return attr . Name === "email" ; } ) ! ; if ( email && ! email . match ( /@example\.com$/ ) ) await new SES ( { apiVersion : "2010-12-01" } ) . sendRawEmail ( { Source : process . env . SES_SENDER_ADDRESS ! , Destinations : [ email ] , RawMessage : { Data : message . toString ( ) } } ) . promise ( ) ; } ) , Promise . resolve ( ) ) ; }