82 lines
2.0 KiB
Go
82 lines
2.0 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/oslstats/internal/db"
|
|
"git.haelnorr.com/h/oslstats/internal/view/page"
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
func SeasonsPage(
|
|
s *hws.Server,
|
|
conn *bun.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "conn.BeginTx"))
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
pageOpts, err := pageOptsFromQuery(r)
|
|
if err != nil {
|
|
throwBadRequest(s, w, r, "invalid query", err)
|
|
return
|
|
}
|
|
seasons, err := db.ListSeasons(ctx, tx, pageOpts)
|
|
if err != nil {
|
|
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "db.ListSeasons"))
|
|
return
|
|
}
|
|
tx.Commit()
|
|
renderSafely(page.SeasonsPage(seasons), s, r, w)
|
|
})
|
|
}
|
|
|
|
func SeasonsList(
|
|
s *hws.Server,
|
|
conn *bun.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
|
|
// Parse form values
|
|
if err := r.ParseForm(); err != nil {
|
|
throwBadRequest(s, w, r, "Invalid form data", err)
|
|
return
|
|
}
|
|
|
|
pageOpts, err := pageOptsFromForm(r)
|
|
if err != nil {
|
|
throwBadRequest(s, w, r, "invalid form data", err)
|
|
return
|
|
}
|
|
|
|
// Database query
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "conn.BeginTx"))
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
|
|
seasons, err := db.ListSeasons(ctx, tx, pageOpts)
|
|
if err != nil {
|
|
throwInternalServiceError(s, w, r, "Database error", errors.Wrap(err, "db.ListSeasons"))
|
|
return
|
|
}
|
|
tx.Commit()
|
|
|
|
// Return only the list component (hx-push-url handles URL update client-side)
|
|
renderSafely(page.SeasonsList(seasons), s, r, w)
|
|
})
|
|
}
|