-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
85 lines (75 loc) · 2.49 KB
/
client.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
package dynago
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
type ClientOptions struct {
TableName string
Region string
PartitionKeyName string
SortKeyName string
Endpoint *EndpointResolver
Middlewares []func(*aws.Config)
}
type Client struct {
client *dynamodb.Client
TableName string
Keys map[string]string
}
type TransactWriteItem types.TransactWriteItem
// Create a new instance of DynamoTable. internally creates aws connection configuration for the db
// If DynamoTable.Endpoint is specified connects to the db at the given URL, or the default credential of the system is used
// To connect to AWS DynamoDB from a running pod or EC2 instance, use the default credentials without Endpoint option
// To connect to a local DynamoDB process, provider Endpoint
//
// table, err := dynamite.NewDynamoTable(dynamite.ClientOptions{
// TableName: "test",
// Endpoint: &dynamite.EndpointResolver{
// EndpointURL: "http://localhost:" + port,
// AccessKeyID: "dummy",
// SecretAccessKey: "dummy",
// },
// PartitionKeyName: "pk",
// SortKeyName: "sk",
// Region: "us-east-1",
// })
func NewClient(ctx context.Context, opt ClientOptions) (*Client, error) {
cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(opt.Region))
// if an endpoint url is provided, connect to the remote/local dynamodb instead of AWS hosted dynamodb
if opt.Endpoint != nil {
cfg, err = config.LoadDefaultConfig(ctx,
config.WithEndpointResolverWithOptions(opt.Endpoint),
config.WithCredentialsProvider(credentials.StaticCredentialsProvider{
Value: aws.Credentials{
AccessKeyID: opt.Endpoint.AccessKeyID,
SecretAccessKey: opt.Endpoint.SecretAccessKey,
},
}))
}
if err != nil {
return nil, fmt.Errorf("unable to load SDK config, %w", err)
}
// aws sdk middlewares, usage tracing
// TODO: better implementation, take a tracer impl and do much more
for _, m := range opt.Middlewares {
m(&cfg)
}
// Using the Config value, create the DynamoDB client
c := dynamodb.NewFromConfig(cfg)
return &Client{
client: c,
TableName: opt.TableName,
Keys: map[string]string{
"pk": opt.PartitionKeyName,
"sk": opt.SortKeyName,
},
}, nil
}
func (t *Client) GetDynamoDBClient() *dynamodb.Client {
return t.client
}