-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrigger.js
62 lines (57 loc) · 1.86 KB
/
trigger.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
'use strict'
const EventBridge = require('aws-sdk/clients/eventbridge')
const DynamoDB = require('aws-sdk/clients/dynamodb')
exports.handler = async function trigger (event) {
const docClient = new DynamoDB.DocumentClient({ convertEmptyValues: true })
const map = docClient.getTranslator()
const Shape = docClient.service.api.operations.getItem.output.members.Item
const changes = event.Records.filter(({ eventName }) =>
['INSERT', 'MODIFY'].includes(eventName)
)
.map(x => map.translateOutput(x.dynamodb.NewImage, Shape))
.reduce((sum, { pk, sk, type, payload, log }) => {
if (!pk.endsWith('#stream')) return sum
sum[log] = sum[log] || []
sum[log].push({ key: { pk, sk }, type, payload })
return sum
}, {})
const eventBridge = new EventBridge({
apiVersion: '2015-10-07',
...(process.env.IS_OFFLINE && {
endpoint: 'http://127.0.0.1:4010',
accessKeyId: 'x',
secretAccessKey: 'x',
region: 'us-east-1'
})
})
for (const [log, items] of Object.entries(changes)) {
while (items.length) {
const batch = items.splice(0, 10)
const params = {
Entries: batch.map(({ key, type, payload }) => {
const detailWithPayload = JSON.stringify({ log, key, type, payload })
const detailLessPayload = JSON.stringify({
log,
key,
type,
partial: true,
payload: {
id: payload.id
}
})
return {
EventBusName: 'dynamodb-log',
Source: 'dynamodb-log',
DetailType: 'stream changes',
Detail:
detailWithPayload.length <= 10240
? detailWithPayload
: detailLessPayload
}
})
}
console.log('putEvents', params)
await eventBridge.putEvents(params).promise()
}
}
}