/
dynamodb.go
78 lines (60 loc) · 1.88 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
package sources
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"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"
)
type DynamoDBSource struct {
Endpoint string `json:"endpoint"`
Region string `json:"region"`
AccessKey string `json:"accessKey"`
SecretKey string `json:"secretKey"`
Table string `json:"table"`
Key string `json:"key"`
}
func (dynamoDBSource *DynamoDBSource) Get() (map[string]interface{}, error) {
config := defaults.Config()
if dynamoDBSource.AccessKey != "" {
config = config.WithCredentials(credentials.NewCredentials(&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: dynamoDBSource.AccessKey,
SecretAccessKey: dynamoDBSource.SecretKey,
},
}))
}
if dynamoDBSource.Endpoint != "" {
config = config.WithEndpoint(dynamoDBSource.Endpoint)
}
if dynamoDBSource.Region != "" {
config = config.WithRegion(dynamoDBSource.Region)
} else {
config = config.WithRegion("us-west-1")
}
client := dynamodb.New(session.New(config))
tableName := aws.String(dynamoDBSource.Table)
describeTableInput := &dynamodb.DescribeTableInput{TableName: tableName}
if _, err := client.DescribeTable(describeTableInput); err != nil {
return nil, err
}
if err := client.WaitUntilTableExists(describeTableInput); err != nil {
return nil, err
}
key := dynamoDBSource.Key
response, err := client.GetItem(&dynamodb.GetItemInput{
Key: map[string]*dynamodb.AttributeValue{
"key": {S: aws.String(key)},
},
TableName: tableName,
ConsistentRead: aws.Bool(true),
})
if err != nil {
return nil, err
}
result := make(map[string]interface{})
err = dynamodbattribute.ConvertFromMap(response.Item, &result)
delete(result, key)
return result, err
}