This repository was archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy_request.go
More file actions
58 lines (46 loc) · 1.78 KB
/
proxy_request.go
File metadata and controls
58 lines (46 loc) · 1.78 KB
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 xlambda
import (
"encoding/json"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/mitchellh/mapstructure"
)
// NewProxyRequest is a helper method to build a events.APIGatewayProxyRequest object.
// You can use this method in tests to mock incoming request payloads to a Lambda function.
func ProxyRequest(method string, queryParameters map[string]string, body interface{}) (*events.APIGatewayProxyRequest, error) {
request := &events.APIGatewayProxyRequest{
HTTPMethod: method,
QueryStringParameters: queryParameters,
}
if body == nil {
return request, nil
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
request.Body = string(data)
return request, nil
}
// ParseAndValidate unmarshals the query string parameters into validatable and then calls
// Validate on it. validatable must be a pointer to an object and cannot be nil.
func ParseAndValidate(request *events.APIGatewayProxyRequest, validatable Validatable) error {
if err := mapstructure.Decode(request.QueryStringParameters, &validatable); err != nil {
return fmt.Errorf("failed to decode query string parameters: %w", err)
}
if err := validatable.Validate(); err != nil {
return fmt.Errorf("validation failed: %w", err)
}
return nil
}
// UnmarshalAndValidate unmarshals the request's body into validatable and then calls Validate
// on it. validatable must be a pointer to an object and cannot be nil.
func UnmarshalAndValidate(request *events.APIGatewayProxyRequest, validatable Validatable) error {
if err := json.Unmarshal([]byte(request.Body), validatable); err != nil {
return fmt.Errorf("failed to unmarshal request body into Validatable: %w", err)
}
if err := validatable.Validate(); err != nil {
return fmt.Errorf("validation failed: %w", err)
}
return nil
}