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

@ -90,7 +90,7 @@ func (ar *AuthRouter) Route(r chi.Router) {
// redirect to frontend with token and refresh token
w.Header().Add("set-cookie", "access_token="+token.AccessToken+"; Path=/; HttpOnly; SameSite=None; Secure; Max-Age=3600")
w.Header().Add("set-cookie", "refresh_token="+token.RefreshToken+"; Path=/; HttpOnly; SameSite=None; Secure")
http.Redirect(w, r, ar.cfg.ClientRedirectURL+"/callback?"+value.Encode(), http.StatusTemporaryRedirect)
http.Redirect(w, r, ar.cfg.ClientRedirectURL+"/?"+value.Encode(), http.StatusTemporaryRedirect)
})
r.Get("/refresh", func(w http.ResponseWriter, r *http.Request) {
@ -110,7 +110,7 @@ func (ar *AuthRouter) Route(r chi.Router) {
}
// redirect to frontend with token and refresh token
http.Redirect(w, r, ar.cfg.ClientRedirectURL+"/callback?token="+token.AccessToken+"&redirect_to="+redirectTo, http.StatusTemporaryRedirect)
http.Redirect(w, r, ar.cfg.ClientRedirectURL+"/?token="+token.AccessToken+"&redirect_to="+redirectTo, http.StatusTemporaryRedirect)
})
r.Get("/revoke", func(w http.ResponseWriter, r *http.Request) {

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,
})
})
})
}