Skip to content
Snippets Groups Projects
Commit 4b7cdade authored by Christian Pointner's avatar Christian Pointner
Browse files

implemented pagination for shows

parent 32030bd8
No related branches found
No related tags found
No related merge requests found
......@@ -26,6 +26,7 @@ package v1
import (
"net/http"
"sort"
"github.com/gin-gonic/gin"
"gitlab.servus.at/autoradio/tank/store"
......@@ -38,10 +39,6 @@ func (api *API) ListShows(c *gin.Context) {
return
}
// TODO: implemement pagination, since the list of shows is rather short
// and the result-set is filtered below we should implement this manually and
// not use the database...
s := getAuthSession(c.Request) // this will panic if there is no session
showsMap := make(map[string]store.Show)
for _, showName := range s.Shows {
......@@ -55,9 +52,33 @@ func (api *API) ListShows(c *gin.Context) {
showsMap[show.Name] = show
}
}
showNames := []string{}
for name, _ := range showsMap {
showNames = append(showNames, name)
}
sort.Strings(showNames)
offset, limit, ok := getPaginationParameter(c)
if !ok {
return
}
result := ShowsListing{}
for _, show := range showsMap {
result.Shows = append(result.Shows, show)
if offset > 0 {
if offset >= len(showNames) {
result.Shows = store.Shows{}
c.JSON(http.StatusOK, result)
return
}
showNames = showNames[offset:]
}
if limit > 0 && limit < len(showNames) {
showNames = showNames[:limit]
}
for _, name := range showNames {
result.Shows = append(result.Shows, showsMap[name])
}
c.JSON(http.StatusOK, result)
......
......@@ -98,6 +98,31 @@ func sendError(c *gin.Context, err error) {
c.JSON(code, response)
}
func parsePositiveIntegerParameter(c *gin.Context, name string) (int, bool) {
valueStr := c.Query(name)
if valueStr == "" {
return -1, true
}
value, err := strconv.Atoi(valueStr)
if err != nil {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: "query parameter " + name + " is invalid: " + err.Error()})
return -1, false
}
if value < 0 {
c.JSON(http.StatusBadRequest, ErrorResponse{Error: "query parameter " + name + " must be >= 0"})
return -1, false
}
return value, true
}
func getPaginationParameter(c *gin.Context) (offset, limit int, ok bool) {
if offset, ok = parsePositiveIntegerParameter(c, "offset"); !ok {
return
}
limit, ok = parsePositiveIntegerParameter(c, "limit")
return
}
func getAuthSession(r *http.Request) *auth.Session {
s, ok := auth.SessionFromRequest(r)
if !ok || s == nil {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment