Redmage/server/routes/api/subreddits_list.go

41 lines
1.1 KiB
Go
Raw Normal View History

2024-04-07 23:41:00 +07:00
package api
import (
"encoding/json"
"fmt"
"net/http"
2024-04-08 23:18:09 +07:00
"strconv"
2024-04-07 23:41:00 +07:00
2024-04-08 23:18:09 +07:00
"github.com/tigorlazuardi/redmage/db/queries/subreddits"
2024-04-07 23:41:00 +07:00
"github.com/tigorlazuardi/redmage/pkg/log"
)
func (api *API) ListSubreddits(rw http.ResponseWriter, r *http.Request) {
rw.Header().Add("Content-Type", "application/json")
2024-04-08 23:18:09 +07:00
subs, err := api.Subreddits.ListSubreddits(r.Context(), parseListSubredditsQuery(r))
2024-04-07 23:41:00 +07:00
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
msg := fmt.Sprintf("failed to list subreddits: %s", err)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": msg})
return
}
if err := json.NewEncoder(rw).Encode(subs); err != nil {
2024-04-08 15:48:45 +07:00
log.New(r.Context()).Err(err).Error("failed to list subreddits")
2024-04-07 23:41:00 +07:00
}
}
2024-04-08 23:18:09 +07:00
func parseListSubredditsQuery(r *http.Request) subreddits.ListSubredditsParams {
params := subreddits.ListSubredditsParams{}
params.Limit, _ = strconv.ParseInt(r.URL.Query().Get("limit"), 10, 64)
params.Offset, _ = strconv.ParseInt(r.URL.Query().Get("offset"), 10, 64)
if params.Limit < 1 {
params.Limit = 10
} else if params.Limit > 100 {
params.Limit = 100
}
return params
}