import { IssuePublicationIdentifier } from '../../common' ; import { Status , putStatus } from './status' ; import moment , { Moment } from 'moment' ; import { sendPublishStatusToTopic , createPublishEvent , PublishEvent , } from './pub-status-notifier' ; import { Handler } from 'aws-lambda' ; import { Attempt } from '../../../backend/utils/try' ; import { PromiseResult } from 'aws-sdk/lib/request' ; import SNS from 'aws-sdk/clients/sns' ; import { AWSError } from 'aws-sdk' ; import { Bucket } from '../utils/s3' ; const errorToString = ( err ) : string => { if ( err instanceof Error ) { return err . toString ( ) ; } return `Error: ${ JSON . stringify ( err ) }` ; } ; type InputWithIdentifier = { issuePublication : IssuePublicationIdentifier ; } ; export type HandlerDependencies = { putStatus : ( issuePublication : IssuePublicationIdentifier , status : Status , bucket : Bucket ) => Promise < { etag : string ; } > ; sendPublishStatusToTopic : ( event : PublishEvent ) => Promise < Attempt < PromiseResult < SNS . PublishResponse , AWSError > > > ; getMoment : ( ) => Moment ; } ; export function handleAndNotifyInternal < I extends InputWithIdentifier , O > ( statusOnSuccess , handler , dependencies , bucket ) { return async ( input ) => { const { issuePublication } = input ; try { console . log ( 'input:' , JSON . stringify ( input ) ) ; const result = await handler ( input ) ; console . log ( 'output:' , JSON . stringify ( result ) ) ; if ( statusOnSuccess != 'errored' ) { await dependencies . putStatus ( issuePublication , statusOnSuccess , bucket ) ; const event = createPublishEvent ( issuePublication , statusOnSuccess , dependencies . getMoment ( ) ) ; await dependencies . sendPublishStatusToTopic ( event ) ; } return result ; } catch ( err ) { const event = { ... issuePublication , status : 'Failed' , message : `${ errorToString ( err ) }` , timestamp : dependencies . getMoment ( ) . format ( ) , } ; await dependencies . sendPublishStatusToTopic ( event ) ; throw err ; } } ; } const runtimeHandlerDependencies = { putStatus , sendPublishStatusToTopic , getMoment : ( ) => moment ( ) , } ; export function handleAndNotify < I extends InputWithIdentifier , O > ( statusOnSuccess , handler , bucket ) { return handleAndNotifyInternal ( statusOnSuccess , handler , runtimeHandlerDependencies , bucket ) ; } export function handleAndNotifyOnError < I extends InputWithIdentifier , O > ( handler , bucket ) { return handleAndNotifyInternal ( 'errored' , handler , runtimeHandlerDependencies , bucket ) ; }