-
Notifications
You must be signed in to change notification settings - Fork 1
/
batch_get_items.go
64 lines (57 loc) · 1.59 KB
/
batch_get_items.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
package dynago
import (
"context"
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)
type AttributeRecord = map[string]Attribute
func chunkBy[T any](items []T, chunkSize int) (chunks [][]T) {
for chunkSize < len(items) {
items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
}
return append(chunks, items)
}
func getBatchResult(ctx context.Context, t *Client, keys []AttributeRecord) ([]AttributeRecord, error) {
var err error
table := t.TableName
items := make([]AttributeRecord, 0, len(keys))
unprocessedKeys := keys
hasMore := true
for hasMore {
input := &dynamodb.BatchGetItemInput{
RequestItems: map[string]types.KeysAndAttributes{
table: {
Keys: unprocessedKeys,
},
},
}
res, err := t.client.BatchGetItem(ctx, input)
if err != nil {
return nil, err
}
items = append(items, res.Responses[table]...)
if res.UnprocessedKeys != nil && len(res.UnprocessedKeys) > 0 {
unprocessedKeys = res.UnprocessedKeys[table].Keys
} else {
hasMore = false
}
}
return items, err
}
func (t *Client) BatchGetItems(ctx context.Context, input []AttributeRecord, out interface{}) (err error) {
var items = make([]AttributeRecord, 0, len(input))
var batches = chunkBy(input, 100)
for _, batch := range batches {
res, err := getBatchResult(ctx, t, batch)
if err != nil {
return err
}
items = append(items, res...)
}
err = attributevalue.UnmarshalListOfMaps(items, &out)
if err != nil {
return err
}
return nil
}