update pagination

This commit is contained in:
Kenta420-Poom 2023-09-25 15:29:42 +07:00
parent 3f399dda0e
commit 51642983c6
15 changed files with 1049 additions and 240 deletions

View file

@ -2,8 +2,12 @@ package routers
import (
"encoding/json"
"log"
"net/http"
"recipe-manager/data"
"recipe-manager/models"
"sort"
"strconv"
"github.com/go-chi/chi/v5"
)
@ -22,7 +26,34 @@ func (rr *RecipeRouter) Route(r chi.Router) {
r.Route("/recipes", func(r chi.Router) {
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
json.NewEncoder(w).Encode(rr.data.GetRecipe())
var take, offset uint64 = 10, 0
if newOffset, err := strconv.ParseUint(r.URL.Query().Get("offset"), 10, 64); err == nil {
offset = newOffset
}
if newTake, err := strconv.ParseUint(r.URL.Query().Get("take"), 10, 64); err == nil {
take = newTake
}
// copy the strcut to avoid modifying the original
recipe := rr.data.GetRecipe()
isHasMore := len(recipe.Recipe01) >= int(take+offset)
if isHasMore {
recipe.Recipe01 = recipe.Recipe01[offset : take+offset]
sort.Slice(recipe.Recipe01, func(i, j int) bool {
return recipe.Recipe01[i].ID < recipe.Recipe01[j].ID
})
} else if len(recipe.Recipe01) > int(offset) {
log.Println("offset", offset, "len", len(recipe.Recipe01))
recipe.Recipe01 = recipe.Recipe01[offset:]
} else {
recipe.Recipe01 = []models.Recipe01{}
}
json.NewEncoder(w).Encode(map[string]interface{}{
"recipes": recipe,
"hasMore": isHasMore,
})
})
})
}