|
| 1 | +import { CloudFormationCustomResourceEvent, Context } from 'aws-lambda'; |
| 2 | +import axios from 'axios'; |
| 3 | +import * as retry from 'async-retry'; |
| 4 | + |
| 5 | +const MAX_RETRIES = 10; |
| 6 | + |
| 7 | +type ResponseStatus = 'SUCCESS' | 'FAILED'; |
| 8 | +export const SUCCESS: ResponseStatus = 'SUCCESS'; |
| 9 | +export const FAILED: ResponseStatus = 'FAILED'; |
| 10 | + |
| 11 | +export function send( |
| 12 | + event: CloudFormationCustomResourceEvent, |
| 13 | + context: Context, |
| 14 | + Status: ResponseStatus, |
| 15 | + Data: any = {}, |
| 16 | + physicalResourceId: any = false, |
| 17 | + NoEcho: any = false |
| 18 | +) { |
| 19 | + const body = JSON.stringify({ |
| 20 | + Status, |
| 21 | + Reason: `See the details in CloudWatch Log Stream: ${context.logStreamName}`, |
| 22 | + PhysicalResourceId: physicalResourceId || context.logStreamName, |
| 23 | + StackId: event.StackId, |
| 24 | + RequestId: event.RequestId, |
| 25 | + LogicalResourceId: event.LogicalResourceId, |
| 26 | + NoEcho, |
| 27 | + Data |
| 28 | + }); |
| 29 | + try { |
| 30 | + sendResponse(event.ResponseURL, body) |
| 31 | + .then(() => { |
| 32 | + console.log('Promise chain success'); |
| 33 | + context.done(); |
| 34 | + }) |
| 35 | + .catch(err => { |
| 36 | + console.error('Promise chain error', err); |
| 37 | + context.done(); |
| 38 | + }); |
| 39 | + console.log('After promise chain'); |
| 40 | + } catch (err) { |
| 41 | + console.log('Try catch error', err); |
| 42 | + } |
| 43 | + console.log('Reached end of sending calls'); |
| 44 | +} |
| 45 | + |
| 46 | +async function retrySendResponse(url, body): Promise<any> { |
| 47 | + console.log('Initiating retry call'); |
| 48 | + return await retry( |
| 49 | + async (abort, attemptCount) => { |
| 50 | + console.log(`Making retry call ${attemptCount} of ${MAX_RETRIES}`); |
| 51 | + await sendResponse(url, body); |
| 52 | + }, |
| 53 | + { retries: MAX_RETRIES } |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +async function sendResponse(url, body): Promise<any> { |
| 58 | + const config = { headers: { 'content-type': '', 'content-length': body.length } }; |
| 59 | + console.log('Making request with params', url, body, config); |
| 60 | + const response = await axios.put(url, body, config); |
| 61 | + console.log('Completed making request', response); |
| 62 | + return response; |
| 63 | +} |
0 commit comments