-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsqs.go
80 lines (73 loc) · 2.44 KB
/
sqs.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
package vesper
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"github.com/aws/aws-lambda-go/events"
"github.com/mefellows/vesper/encoding"
)
// SQSParserMiddleware transforms SQS event records into the handler input parameter type using the given unmarshaler.
// The handler input parameter must be a slice.
func SQSParserMiddleware(unmarshaler encoding.UnmarshalFunc) func(LambdaFunc) LambdaFunc {
validateTIn := func(tIn reflect.Type) error {
if tIn == reflect.TypeOf(events.SQSEvent{}) {
return errors.New("SQSParserMiddleware middleware should not be used if input parameter is events.SQSEvent")
}
if tIn.Kind() != reflect.Slice {
return errors.New("input parameter for SQS event must be a slice")
}
return nil
}
unmarshalSQSEvent := func(in interface{}) (events.SQSEvent, error) {
b, ok := in.([]byte)
if !ok {
return events.SQSEvent{}, fmt.Errorf("expected []byte input but got %T", in)
}
evt := events.SQSEvent{}
if err := json.Unmarshal(b, &evt); err != nil {
return events.SQSEvent{}, fmt.Errorf("could not unmarshal SQS event: %w", err)
}
return evt, nil
}
unmarshalRecords := func(tIn reflect.Type, evt events.SQSEvent) (reflect.Value, error) {
tIns := reflect.MakeSlice(tIn, 0, len(evt.Records))
for _, r := range evt.Records {
msgBody, err := unmarshalToType(unmarshaler, tIn.Elem(), []byte(r.Body))
if err != nil {
return reflect.Value{}, fmt.Errorf("could not unmarshal SQS message body for ID %s: %w", r.MessageId, err)
}
tIns = reflect.Append(tIns, reflect.ValueOf(msgBody))
}
return tIns, nil
}
return func(next LambdaFunc) LambdaFunc {
return func(ctx context.Context, in interface{}) (interface{}, error) {
if unmarshaler == nil {
return nil, errors.New("no unmarshaler was provided")
}
tIn, ok := TInFromContext(ctx)
if !ok {
return next(ctx, in) // continue as there is no TIn to parse anyway.
}
if err := validateTIn(tIn); err != nil {
return nil, err
}
evt, err := unmarshalSQSEvent(in)
if err != nil {
return nil, err
}
tIns, err := unmarshalRecords(tIn, evt)
if err != nil {
return nil, err
}
return next(ctx, tIns.Interface())
}
}
}
// JSONSQSParserMiddleware transforms SQS event records into the handler input parameter type using a JSON unmarshaler.
// The handler input parameter must be a slice.
func JSONSQSParserMiddleware() func(LambdaFunc) LambdaFunc {
return SQSParserMiddleware(json.Unmarshal)
}