-
Notifications
You must be signed in to change notification settings - Fork 21
/
dynamodb.go
79 lines (64 loc) · 2.1 KB
/
dynamodb.go
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
71
72
73
74
75
76
77
78
79
package handlers
import (
"context"
"encoding/json"
"log"
"github.com/aws-samples/serverless-go-demo/domain"
"github.com/aws-samples/serverless-go-demo/types"
"github.com/aws/aws-lambda-go/events"
)
type DynamoDBEventHandler struct {
productStream *domain.ProductsStream
}
// Can be deleted when this is merged: https://github.com/aws/aws-lambda-go/pull/410/files
type StreamsEventResponse struct {
BatchItemFailures []BatchItemFailure `json:"batchItemFailures"`
}
type BatchItemFailure struct {
ItemIdentifier string `json:"itemIdentifier"`
}
func NewDynamoDBEventHandler(p *domain.ProductsStream) *DynamoDBEventHandler {
return &DynamoDBEventHandler{
productStream: p,
}
}
func (d *DynamoDBEventHandler) StreamHandler(ctx context.Context, event events.DynamoDBEvent) (StreamsEventResponse, error) {
internalEvents := make([]types.Event, len(event.Records))
for i, ddbEvent := range event.Records {
internalEvents[i] = eventFromDynamoDBRecord(ddbEvent)
}
failedEvents, err := d.productStream.Publish(ctx, internalEvents)
if err != nil {
log.Fatalf("totally failed to publish: %v", err)
return StreamsEventResponse{}, err
}
if len(failedEvents) > 0 {
itemFailures := make([]BatchItemFailure, len(failedEvents))
for i, failedItem := range failedEvents {
itemFailures[i] = BatchItemFailure{ItemIdentifier: failedItem.Resources[0]}
}
return StreamsEventResponse{BatchItemFailures: itemFailures}, nil
}
return StreamsEventResponse{}, nil
}
func eventFromDynamoDBRecord(record events.DynamoDBEventRecord) types.Event {
change, err := json.Marshal(record.Change)
if err != nil {
log.Fatalf("cannot unmarshal dynamodb record change: %s", err)
}
detailType := ""
switch record.EventName {
case string(events.DynamoDBOperationTypeInsert):
detailType = "ProductCreated"
case string(events.DynamoDBOperationTypeModify):
detailType = "ProductUpdated"
case string(events.DynamoDBOperationTypeRemove):
detailType = "ProductDelected"
}
return types.Event{
Source: "serverless-go-demo",
Detail: string(change),
DetailType: detailType,
Resources: []string{record.EventID},
}
}