-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfield_loader.go
73 lines (67 loc) · 1.77 KB
/
field_loader.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
package dynamodb
import (
"context"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/expression"
)
type FieldLoader struct {
database *dynamodb.DynamoDB
tableName string
name string
}
func NewFieldLoader(db *dynamodb.DynamoDB, tableName string, name string) *FieldLoader {
return &FieldLoader{
database: db,
tableName: tableName,
name: name,
}
}
func (l *FieldLoader) Values(ctx context.Context, ids []string) ([]string, error) {
var array []string
projection := expression.NamesList(expression.Name(l.name))
var filterConditions *expression.ConditionBuilder
for _, id := range ids {
c := expression.Equal(expression.Name(l.name), expression.Value(id))
if filterConditions == nil {
filterConditions = &c
} else {
and := filterConditions.Or(c)
filterConditions = &and
}
}
expr, err := expression.NewBuilder().
WithFilter(*filterConditions).
WithProjection(projection).
Build()
if err != nil {
return nil, err
}
query := &dynamodb.ScanInput{
TableName: aws.String(l.tableName),
ProjectionExpression: expr.Projection(),
FilterExpression: expr.Filter(),
ExpressionAttributeNames: expr.Names(),
ExpressionAttributeValues: expr.Values(),
}
if err != nil {
return nil, err
}
output, err := l.database.ScanWithContext(ctx, query)
if err != nil {
return array, err
}
if len(output.Items) == 0 {
return array, nil
}
var result []map[string]interface{}
err = dynamodbattribute.UnmarshalListOfMaps(output.Items, &result)
if err != nil {
return array, err
}
for _, model := range result {
array = append(array, model[l.name].(string))
}
return array, err
}