From 0986a409d82c418c37461b587210b021e8577c92 Mon Sep 17 00:00:00 2001 From: Trim21 Date: Tue, 26 Nov 2024 00:52:26 +0800 Subject: [PATCH] fix!: reduce search page limit to 20 --- internal/search/handle.go | 2 +- web/req/page.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/search/handle.go b/internal/search/handle.go index 76818d284..44061308a 100644 --- a/internal/search/handle.go +++ b/internal/search/handle.go @@ -105,7 +105,7 @@ type ReponseSubject struct { //nolint:funlen func (c *client) Handle(ctx echo.Context) error { auth := accessor.GetFromCtx(ctx) - q, err := req.GetPageQuery(ctx, defaultLimit, maxLimit) + q, err := req.GetPageQuerySoftLimit(ctx, defaultLimit, maxLimit) if err != nil { return err } diff --git a/web/req/page.go b/web/req/page.go index c0e1de94b..18e719ac1 100644 --- a/web/req/page.go +++ b/web/req/page.go @@ -35,6 +35,42 @@ func (q PageQuery) Check(count int64) error { return nil } +// GetPageQuerySoftLimit apply soft limit on query without error. +func GetPageQuerySoftLimit(c echo.Context, defaultLimit int, maxLimit int) (PageQuery, error) { + q := PageQuery{Limit: defaultLimit} + var err error + + raw := c.QueryParam("limit") + if raw != "" { + q.Limit, err = strconv.Atoi(raw) + if err != nil { + return q, res.BadRequest("can't parse query args limit as int: " + strconv.Quote(raw)) + } + + if q.Limit <= 0 { + return q, res.BadRequest("limit should be greater than zero") + } + + if q.Limit > maxLimit { + q.Limit = maxLimit + } + } + + raw = c.QueryParam("offset") + if raw != "" { + q.Offset, err = strconv.Atoi(raw) + if err != nil { + return q, res.BadRequest("can't parse query args offset as int: " + strconv.Quote(raw)) + } + + if q.Offset < 0 { + return q, res.BadRequest("offset should be greater than or equal to 0") + } + } + + return q, nil +} + func GetPageQuery(c echo.Context, defaultLimit int, maxLimit int) (PageQuery, error) { q := PageQuery{Limit: defaultLimit} var err error