fix: improve pagination parser (#12422)

This commit is contained in:
Marcin Tojek
2024-03-05 15:05:15 +01:00
committed by GitHub
parent 61db293b33
commit 3e99c0373f
5 changed files with 101 additions and 7 deletions

View File

@ -79,6 +79,30 @@ func (p *QueryParamParser) Int(vals url.Values, def int, queryParam string) int
return v
}
// PositiveInt32 function checks if the given value is 32-bit and positive.
//
// We can't use `uint32` as the value must be within the range <0,2147483647>
// as database expects it. Otherwise, the database query fails with `pq: OFFSET must not be negative`.
func (p *QueryParamParser) PositiveInt32(vals url.Values, def int32, queryParam string) int32 {
v, err := parseQueryParam(p, vals, func(v string) (int32, error) {
intValue, err := strconv.ParseInt(v, 10, 32)
if err != nil {
return 0, err
}
if intValue < 0 {
return 0, xerrors.Errorf("value is negative")
}
return int32(intValue), nil
}, def, queryParam)
if err != nil {
p.Errors = append(p.Errors, codersdk.ValidationError{
Field: queryParam,
Detail: fmt.Sprintf("Query param %q must be a valid 32-bit positive integer (%s)", queryParam, err.Error()),
})
}
return v
}
func (p *QueryParamParser) Boolean(vals url.Values, def bool, queryParam string) bool {
v, err := parseQueryParam(p, vals, strconv.ParseBool, def, queryParam)
if err != nil {

View File

@ -236,6 +236,50 @@ func TestParseQueryParams(t *testing.T) {
testQueryParams(t, expParams, parser, parser.Int)
})
t.Run("PositiveInt32", func(t *testing.T) {
t.Parallel()
expParams := []queryParamTestCase[int32]{
{
QueryParam: "valid_integer",
Value: "100",
Expected: 100,
},
{
QueryParam: "empty",
Value: "",
Expected: 0,
},
{
QueryParam: "no_value",
NoSet: true,
Default: 5,
Expected: 5,
},
{
QueryParam: "negative",
Value: "-1",
Expected: 0,
Default: 5,
ExpectedErrorContains: "must be a valid 32-bit positive integer",
},
{
QueryParam: "invalid_integer",
Value: "bogus",
Expected: 0,
ExpectedErrorContains: "must be a valid 32-bit positive integer",
},
{
QueryParam: "max_int_plus_one",
Value: "2147483648",
Expected: 0,
ExpectedErrorContains: "must be a valid 32-bit positive integer",
},
}
parser := httpapi.NewQueryParamParser()
testQueryParams(t, expParams, parser, parser.PositiveInt32)
})
t.Run("UInt", func(t *testing.T) {
t.Parallel()
expParams := []queryParamTestCase[uint64]{