-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract_key_fn.go
58 lines (46 loc) · 1.17 KB
/
extract_key_fn.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
package dofns
import (
"context"
"fmt"
"reflect"
"github.com/apache/beam/sdks/v2/go/pkg/beam"
"github.com/apache/beam/sdks/v2/go/pkg/beam/register"
)
func init() {
register.DoFn3x1[context.Context, beam.X, func(string, beam.X), error](&ExtractKeyFn{})
register.Emitter2[string, beam.X]()
}
type ExtractKeyFn struct {
KeyField string
Type beam.EncodedType
}
func NewExtractKeyFn(keyField string, elemType reflect.Type) *ExtractKeyFn {
return &ExtractKeyFn{
KeyField: keyField,
Type: beam.EncodedType{T: elemType},
}
}
func (fn *ExtractKeyFn) ProcessElement(
_ context.Context,
elem beam.X,
emit func(string, beam.X),
) error {
val := reflect.ValueOf(elem)
kind := val.Kind()
if kind != reflect.Struct {
return fmt.Errorf("element must be a struct but was: %v", kind)
}
key, err := extractKey(val, fn.KeyField)
if err != nil {
return fmt.Errorf("error extracting key: %w", err)
}
emit(key, elem)
return nil
}
func extractKey(val reflect.Value, keyField string) (string, error) {
field := val.FieldByName(keyField)
if field == (reflect.Value{}) {
return "", fmt.Errorf("element has no field with name %q", keyField)
}
return field.String(), nil
}