/
storage.go
82 lines (72 loc) · 2.04 KB
/
storage.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
package battlestrg
import (
"context"
"fmt"
"github.com/Haraj-backend/hex-monscape/internal/core/entity"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"gopkg.in/validator.v2"
)
type Storage struct {
dynamoClient *dynamodb.DynamoDB
tableName string
}
func (s *Storage) GetBattle(ctx context.Context, gameID string) (*entity.Battle, error) {
// construct params
key := battleKey{GameID: gameID}
input := &dynamodb.GetItemInput{
TableName: aws.String(s.tableName),
Key: key.toDDBKey(),
}
// execute get item
output, err := s.dynamoClient.GetItemWithContext(ctx, input)
if err != nil {
return nil, fmt.Errorf("unable to get item from %s due to: %w", s.tableName, err)
}
// if item is not found, returns nil as expected by battle interface
if len(output.Item) == 0 {
return nil, nil
}
// parse item
var battleRow battleRow
err = dynamodbattribute.UnmarshalMap(output.Item, &battleRow)
if err != nil {
return nil, fmt.Errorf("unable to unmarshal item from %s due to: %w", s.tableName, err)
}
battle := battleRow.toBattle()
return battle, nil
}
func (s *Storage) SaveBattle(ctx context.Context, b entity.Battle) error {
// construct params
item, _ := dynamodbattribute.MarshalMap(toBattleRow(b))
input := &dynamodb.PutItemInput{
TableName: aws.String(s.tableName),
Item: item,
}
// execute put item
_, err := s.dynamoClient.PutItemWithContext(ctx, input)
if err != nil {
return fmt.Errorf("unable to put item to %s due to: %w", s.tableName, err)
}
return nil
}
type Config struct {
DynamoClient *dynamodb.DynamoDB `validate:"nonnil"`
TableName string `validate:"nonzero"`
}
func (c Config) Validate() error {
return validator.Validate(c)
}
// New returns new instance of battlestrg dynamoDB Storage
func New(cfg Config) (*Storage, error) {
err := cfg.Validate()
if err != nil {
return nil, err
}
strg := &Storage{
dynamoClient: cfg.DynamoClient,
tableName: cfg.TableName,
}
return strg, nil
}