pronounscc/backend/routes/mod/get_reports.go

85 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-03-19 16:14:09 +01:00
package mod
import (
"net/http"
2023-03-21 14:27:39 +01:00
"strconv"
2023-06-03 16:18:47 +02:00
"codeberg.org/pronounscc/pronouns.cc/backend/log"
"codeberg.org/pronounscc/pronouns.cc/backend/server"
2023-03-21 14:27:39 +01:00
"emperror.dev/errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/rs/xid"
2023-03-19 16:14:09 +01:00
)
2023-03-21 14:27:39 +01:00
func (s *Server) getReports(w http.ResponseWriter, r *http.Request) (err error) {
ctx := r.Context()
2023-03-19 16:14:09 +01:00
showClosed := r.FormValue("closed") == "true"
2023-03-21 14:27:39 +01:00
var before int
if s := r.FormValue("before"); s != "" {
before, err = strconv.Atoi(s)
if err != nil {
return server.APIError{Code: server.ErrBadRequest, Details: "\"before\": invalid ID"}
}
}
reports, err := s.DB.Reports(ctx, showClosed, before)
if err != nil {
log.Errorf("getting reports: %v", err)
return errors.Wrap(err, "getting reports from database")
}
render.JSON(w, r, reports)
return nil
}
func (s *Server) getReportsByUser(w http.ResponseWriter, r *http.Request) (err error) {
ctx := r.Context()
var before int
if s := r.FormValue("before"); s != "" {
before, err = strconv.Atoi(s)
if err != nil {
return server.APIError{Code: server.ErrBadRequest, Details: "\"before\": invalid ID"}
}
}
userID, err := xid.FromString(chi.URLParam(r, "id"))
if err != nil {
return server.APIError{Code: server.ErrBadRequest, Details: "Invalid user ID"}
}
reports, err := s.DB.ReportsByUser(ctx, userID, before)
if err != nil {
log.Errorf("getting reports: %v", err)
return errors.Wrap(err, "getting reports from database")
}
render.JSON(w, r, reports)
return nil
}
func (s *Server) getReportsByReporter(w http.ResponseWriter, r *http.Request) (err error) {
ctx := r.Context()
var before int
if s := r.FormValue("before"); s != "" {
before, err = strconv.Atoi(s)
if err != nil {
return server.APIError{Code: server.ErrBadRequest, Details: "\"before\": invalid ID"}
}
}
userID, err := xid.FromString(chi.URLParam(r, "id"))
if err != nil {
return server.APIError{Code: server.ErrBadRequest, Details: "Invalid user ID"}
}
reports, err := s.DB.ReportsByReporter(ctx, userID, before)
if err != nil {
log.Errorf("getting reports: %v", err)
return errors.Wrap(err, "getting reports from database")
}
2023-03-19 16:14:09 +01:00
2023-03-21 14:27:39 +01:00
render.JSON(w, r, reports)
2023-03-19 16:14:09 +01:00
return nil
}