Files
Deflated/internal/handlers/items.go
T

80 lines
2.1 KiB
Go

package handlers
import (
"log/slog"
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"git.seaofstars.xyz/mohd/deflated/internal/db"
)
// ItemHandler handles routes that return price and inflation data.
type ItemHandler struct {
queries *db.Queries
}
func NewItemHandler(queries *db.Queries) *ItemHandler {
return &ItemHandler{queries: queries}
}
// List handles GET /api/items
func (h *ItemHandler) List(w http.ResponseWriter, r *http.Request) {
items, err := h.queries.ListCanonicalItems(r.Context())
if err != nil {
slog.Error("list items", "error", err)
writeError(w, http.StatusInternalServerError, "database error")
return
}
writeJSON(w, http.StatusOK, items)
}
// PriceHistory handles GET /api/items/{name}/history
func (h *ItemHandler) PriceHistory(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
history, err := h.queries.GetPriceHistory(r.Context(), name)
if err != nil {
slog.Error("get price history", "error", err, "name", name)
writeError(w, http.StatusInternalServerError, "database error")
return
}
writeJSON(w, http.StatusOK, history)
}
// TopMovers handles GET /api/items/top-movers?months=12&limit=10
func (h *ItemHandler) TopMovers(w http.ResponseWriter, r *http.Request) {
months, _ := strconv.Atoi(r.URL.Query().Get("months"))
if months <= 0 {
months = 12
}
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if limit <= 0 {
limit = 10
}
movers, err := h.queries.GetTopMovers(r.Context(), months, limit)
if err != nil {
slog.Error("get top movers", "error", err)
writeError(w, http.StatusInternalServerError, "database error")
return
}
writeJSON(w, http.StatusOK, movers)
}
// InflationSummary handles GET /api/inflation/summary?base_year=2009
func (h *ItemHandler) InflationSummary(w http.ResponseWriter, r *http.Request) {
baseYear, _ := strconv.Atoi(r.URL.Query().Get("base_year"))
if baseYear <= 0 {
baseYear = 2009
}
summary, err := h.queries.GetInflationSummary(r.Context(), baseYear)
if err != nil {
slog.Error("get inflation summary", "error", err)
writeError(w, http.StatusInternalServerError, "database error")
return
}
writeJSON(w, http.StatusOK, summary)
}