-
Notifications
You must be signed in to change notification settings - Fork 16
/
apigw-handler.js
70 lines (63 loc) · 2.06 KB
/
apigw-handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use strict'
const axios = require('axios').default
module.exports = {
handleGet,
handleSubscription
}
/**
* A simple Lambda that can be used to test metrics and alarms for different status codes and response times
*/
async function handleGet (event) {
const qs = event.queryStringParameters || {}
const timeout = Number(qs.timeout) || 1000
const statusCode = Number(qs.statusCode) || 200
await new Promise((resolve) => {
setTimeout(() => resolve(), timeout)
})
return { statusCode }
}
/**
* This Lambda function handler allows us to provide an HTTP endpoint for SNS HTTP(S) subscriptions.
* It handles two event types:
* - Message subscription confirmation flow, where SNS requires the HTTPS endpoint to validate the subscription.
* - Message delivery
*
* In the case of message delivery, we can also simulate message delivery failures. If the message payload has `fail: true`,
* we will return a 500 status code.
*
* @param {object} event The Lambda event
* @returns The API Gateway Lambda Proxy response
*/
async function handleSubscription (event) {
console.log(event)
const eventBody = JSON.parse(event.body)
const result = {}
try {
if (eventBody.Type === 'SubscriptionConfirmation') {
const res = await axios.get(eventBody.SubscribeURL)
console.log('Subscription confirmation response', { statusCode: res.status, statusText: res.statusText })
result.statusCode = res.status
} else {
let messageBody
try {
// Support JSON messages
messageBody = JSON.parse(eventBody.Message)
} catch (err) {
// Fallback to plain text
messageBody = eventBody.Message
}
if (messageBody.fail === true) {
console.log('fail is set to true, simulating message delivery failure')
result.statusCode = 500
} else {
console.log('Successful message delivery')
result.statusCode = 200
}
}
} catch (err) {
console.error('Unexpected error received', err)
result.statusCode = 500
}
console.log('Returning result', result)
return result
}