File size: 2,098 Bytes
ea775bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package api

import (
	"errors"
	"fmt"
	"io"
	"net/http"
)

func parsePaginationOrWriteInvalid(w http.ResponseWriter, r *http.Request) (Pagination, bool) {
	pg, err := ParsePagination(r)
	if err != nil {
		writeInvalidArgument(w, err.Error())
		return Pagination{}, false
	}
	return pg, true
}

func parseSortingOrWriteInvalid(
	w http.ResponseWriter,
	r *http.Request,
	allowed []string,
	defaultField string,
	defaultOrder string,
) (Sorting, bool) {
	s, err := ParseSorting(r, allowed, defaultField, defaultOrder)
	if err != nil {
		writeInvalidArgument(w, err.Error())
		return Sorting{}, false
	}
	return s, true
}

func parseBoolQueryOrWriteInvalid(w http.ResponseWriter, r *http.Request, key string) (*bool, bool) {
	v, err := ParseBoolQuery(r, key)
	if err != nil {
		writeInvalidArgument(w, err.Error())
		return nil, false
	}
	return v, true
}

func readRawBodyOrWriteInvalid(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
	if r.Body == nil {
		writeInvalidArgument(w, "request body is required")
		return nil, false
	}
	body, err := io.ReadAll(r.Body)
	if err != nil {
		var maxErr *http.MaxBytesError
		if errors.As(err, &maxErr) {
			writePayloadTooLarge(w, maxErr.Limit)
			return nil, false
		}
		writeInvalidArgument(w, "failed to read body")
		return nil, false
	}
	return body, true
}

func requireUUIDPathParam(
	w http.ResponseWriter,
	r *http.Request,
	paramName string,
	fieldName string,
) (string, bool) {
	value := PathParam(r, paramName)
	if !ValidateUUID(value) {
		writeInvalidArgument(w, fmt.Sprintf("%s: must be a valid UUID", fieldName))
		return "", false
	}
	return value, true
}

func parseOptionalUUIDQuery(
	w http.ResponseWriter,
	r *http.Request,
	queryKey string,
	fieldName string,
) (*string, bool) {
	value := r.URL.Query().Get(queryKey)
	if value == "" {
		return nil, true
	}
	if !ValidateUUID(value) {
		writeInvalidArgument(w, fmt.Sprintf("%s: must be a valid UUID", fieldName))
		return nil, false
	}
	return &value, true
}

func applySortOrder(order int, sortOrder string) int {
	if sortOrder == "desc" {
		return -order
	}
	return order
}