-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
69 lines (59 loc) · 1.51 KB
/
db.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
package main
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
)
// Declare a new DynamoDB instance. Note that this is safe for concurrent
// use.
var db = dynamodb.New(session.New(), aws.NewConfig().WithRegion("eu-west-2"))
func getItem(id string) (*user, error) {
// Prepare the input for the query.
input := &dynamodb.GetItemInput{
TableName: aws.String("Users"),
Key: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(id),
},
},
}
// Retrieve the item from DynamoDB. If no matching item is found
// return nil.
result, err := db.GetItem(input)
if err != nil {
return nil, err
}
if result.Item == nil {
return nil, nil
}
// The result.Item object returned has the underlying type
// map[string]*AttributeValue. We can use the UnmarshalMap helper
// to parse this straight into the fields of a struct. Note:
// UnmarshalListOfMaps also exists if you are working with multiple
// items.
u := new(user)
err = dynamodbattribute.UnmarshalMap(result.Item, u)
if err != nil {
return nil, err
}
return u, nil
}
func putItem(u *user) error {
input := &dynamodb.PutItemInput{
TableName: aws.String("Users"),
Item: map[string]*dynamodb.AttributeValue{
"ID": {
S: aws.String(u.ID),
},
"Name": {
S: aws.String(u.Name),
},
"Hobbies": {
S: aws.String(u.Hobbies),
},
},
}
_, err := db.PutItem(input)
return err
}