-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (69 loc) · 1.86 KB
/
main.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
80
81
package main
import (
"context"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
)
type Transaction struct {
Id int `json:"id"`
Amount int `json:"amount"`
State string `json:"state"`
}
func handler(ctx context.Context, sqsEvent events.SQSEvent) error {
/* Create aws config, in our case we should connect to local aws */
config := aws.Config{Endpoint: aws.String("http://localhost:4566")}
/* creates DynamoDB session */
sess, err := session.NewSession(&config)
if err != nil {
fmt.Errorf("failed to create session: %v", err)
return err
}
ddb := dynamodb.New(sess)
/* Process SQS events to store our data in DynamoDG */
for _, record := range sqsEvent.Records {
body := record.Body
/* Parse string body as Json and map it our Transaction model */
var transaction Transaction
err := json.Unmarshal([]byte(body), &transaction)
if err != nil {
fmt.Println("Error parsing JSON:", err)
return err
}
/* current timestamp nanoSecond as string */
currentTime := strconv.FormatInt(time.Now().UnixNano(), 10)
/* Create the object we are going to store into the DynamoDB */
input := &dynamodb.PutItemInput{
TableName: aws.String("PaymentsStates"),
Item: map[string]*dynamodb.AttributeValue{
"id": {
N: aws.String(strconv.Itoa(transaction.Id)),
},
"timestamp": {
S: aws.String(currentTime),
},
"amount": {
N: aws.String(strconv.Itoa(transaction.Amount)),
},
"state": {
S: aws.String(transaction.State),
},
},
}
_, err = ddb.PutItem(input)
if err != nil {
fmt.Errorf("failed to put item into DynamoDB: %v", err)
return err
}
}
return nil
}
func main() {
lambda.Start(handler)
}