59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package routers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"recipe-manager/data"
|
|
"recipe-manager/models"
|
|
"sort"
|
|
"strconv"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
type RecipeRouter struct {
|
|
data *data.Data
|
|
}
|
|
|
|
func NewRecipeRouter(data *data.Data) *RecipeRouter {
|
|
return &RecipeRouter{
|
|
data: data,
|
|
}
|
|
}
|
|
|
|
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")
|
|
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,
|
|
})
|
|
})
|
|
})
|
|
}
|