-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamodb.go
105 lines (93 loc) · 2.06 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package haveibeenbreached
import (
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
var tableName = os.Getenv("BREACHES_TABLE")
type DBItem interface {
isDBItem() bool
}
type Itemable interface {
ToItem() DBItem
}
type Repo struct {
db *dynamodb.DynamoDB
}
func NewRepo(db *dynamodb.DynamoDB) Repo {
return Repo{db}
}
func (r Repo) GetAccount(username Username) (*Account, error) {
pk := username.PartitionKey()
sk := username.SortKey()
accountItem := AccountItem{}
found, err := r.getItem(pk, sk, &accountItem)
if err != nil {
return nil, err
}
if !found {
return nil, nil
}
account, err := accountItem.ToAccount()
if err != nil {
return nil, err
}
return &account, nil
}
func (r Repo) GetBreach(breachName string) (*Breach, error) {
pk := BreachPartitionKey(breachName)
sk := BreachSortKey(breachName)
breachItem := BreachItem{}
found, err := r.getItem(pk, sk, &breachItem)
if err != nil {
return nil, err
}
if !found {
return nil, nil
}
breach := breachItem.ToBreach()
return &breach, nil
}
func (r Repo) getItem(partitionKey string, sortKey string, output interface{}) (found bool, err error) {
input := &dynamodb.GetItemInput{
TableName: aws.String(tableName),
Key: map[string]*dynamodb.AttributeValue{
"PK": {
S: aws.String(partitionKey),
},
"SK": {
S: aws.String(sortKey),
},
},
}
result, err := r.db.GetItem(input)
if err != nil {
return false, err
}
if result.Item != nil {
err := dynamodbattribute.UnmarshalMap(result.Item, output)
return true, err
}
return false, nil
}
func (r Repo) PutItem(itemable Itemable) error {
attrVal, err := dynamodbattribute.MarshalMap(itemable.ToItem())
if err != nil {
return err
}
input := &dynamodb.PutItemInput{
Item: attrVal,
TableName: aws.String(tableName),
}
_, err = r.db.PutItem(input)
return err
}
func (r Repo) PutItems(items []Itemable) error {
for _, item := range items {
if err := r.PutItem(item); err != nil {
return err
}
}
return nil
}