Changed ReadAll method to enable proper pagination

This commit is contained in:
kolaente 2019-10-21 23:04:17 +02:00
parent b457b5a1a3
commit 75c50a705f
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
3 changed files with 27 additions and 4 deletions

View File

@ -24,6 +24,7 @@ import (
type Config struct { type Config struct {
AuthProvider *web.Auths AuthProvider *web.Auths
LoggingProvider *logging.Logger LoggingProvider *logging.Logger
MaxItemsPerPage int64
} }
var config *Config var config *Config

View File

@ -41,7 +41,7 @@ func (c *WebHandler) ReadAllWeb(ctx echo.Context) error {
if page == "" { if page == "" {
page = "1" page = "1"
} }
pageNumber, err := strconv.Atoi(page) pageNumber, err := strconv.ParseInt(page, 10, 64)
if err != nil { if err != nil {
config.LoggingProvider.Error(err.Error()) config.LoggingProvider.Error(err.Error())
return echo.NewHTTPError(http.StatusBadRequest, "Bad page requested.") return echo.NewHTTPError(http.StatusBadRequest, "Bad page requested.")
@ -50,13 +50,35 @@ func (c *WebHandler) ReadAllWeb(ctx echo.Context) error {
return echo.NewHTTPError(http.StatusBadRequest, "Bad page requested.") return echo.NewHTTPError(http.StatusBadRequest, "Bad page requested.")
} }
// Items per page
perPage := ctx.QueryParam("per_page")
perPageNumber, err := strconv.ParseInt(perPage, 10, 64)
if err != nil {
config.LoggingProvider.Error(err.Error())
return echo.NewHTTPError(http.StatusBadRequest, "Bad per page amount requested.")
}
// Set default page count
if perPageNumber == 0 {
perPageNumber = config.MaxItemsPerPage
}
if perPageNumber < 1 {
return echo.NewHTTPError(http.StatusBadRequest, "Bad per page amount requested.")
}
if perPageNumber > config.MaxItemsPerPage {
perPageNumber = config.MaxItemsPerPage
}
// Search // Search
search := ctx.QueryParam("s") search := ctx.QueryParam("s")
lists, err := currentStruct.ReadAll(search, currentAuth, pageNumber) result, resultCount, numberOfPages, err := currentStruct.ReadAll(currentAuth, search, pageNumber, perPageNumber)
if err != nil { if err != nil {
return HandleHTTPError(err, ctx) return HandleHTTPError(err, ctx)
} }
return ctx.JSON(http.StatusOK, lists) ctx.Response().Header().Set("x-pagination-total-pages", strconv.FormatInt(numberOfPages, 10))
ctx.Response().Header().Set("x-pagination-result-count", strconv.FormatInt(resultCount, 10))
ctx.Response().Header().Set("Access-Control-Expose-Headers", "x-pagination-total-pages, x-pagination-result-count")
return ctx.JSON(http.StatusOK, result)
} }

2
web.go
View File

@ -31,7 +31,7 @@ type Rights interface {
type CRUDable interface { type CRUDable interface {
Create(Auth) error Create(Auth) error
ReadOne() error ReadOne() error
ReadAll(string, Auth, int) (interface{}, error) ReadAll(auth Auth, search string, page int64, perPage int64) (result interface{}, resultCount int64, numberOfPages int64, err error)
Update() error Update() error
Delete() error Delete() error
} }