Files
spend-sparrow/internal/handler/account.go
Tim Wundenberg 6291700a3b
All checks were successful
Build Docker Image / Build-Docker-Image (push) Successful in 8m11s
feat(observabillity): #153 instrument sqlx
2025-06-07 21:55:59 +02:00

145 lines
2.8 KiB
Go

package handler
import (
"net/http"
"spend-sparrow/internal/handler/middleware"
"spend-sparrow/internal/service"
t "spend-sparrow/internal/template/account"
"spend-sparrow/internal/types"
"spend-sparrow/internal/utils"
"github.com/a-h/templ"
)
type Account interface {
Handle(router *http.ServeMux)
}
type AccountImpl struct {
s service.Account
r *Render
}
func NewAccount(s service.Account, r *Render) Account {
return AccountImpl{
s: s,
r: r,
}
}
func (h AccountImpl) Handle(r *http.ServeMux) {
r.Handle("GET /account", h.handleAccountPage())
r.Handle("GET /account/{id}", h.handleAccountItemComp())
r.Handle("POST /account/{id}", h.handleUpdateAccount())
r.Handle("DELETE /account/{id}", h.handleDeleteAccount())
}
func (h AccountImpl) handleAccountPage() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updateSpan(r)
user := middleware.GetUser(r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
accounts, err := h.s.GetAll(r.Context(), user)
if err != nil {
handleError(w, r, err)
return
}
comp := t.Account(accounts)
h.r.RenderLayout(r, w, comp, user)
}
}
func (h AccountImpl) handleAccountItemComp() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updateSpan(r)
user := middleware.GetUser(r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
id := r.PathValue("id")
if id == "new" {
comp := t.EditAccount(nil)
h.r.Render(r, w, comp)
return
}
account, err := h.s.Get(r.Context(), user, id)
if err != nil {
handleError(w, r, err)
return
}
var comp templ.Component
if r.URL.Query().Get("edit") == "true" {
comp = t.EditAccount(account)
} else {
comp = t.AccountItem(account)
}
h.r.Render(r, w, comp)
}
}
func (h AccountImpl) handleUpdateAccount() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updateSpan(r)
user := middleware.GetUser(r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
var (
account *types.Account
err error
)
id := r.PathValue("id")
name := r.FormValue("name")
if id == "new" {
account, err = h.s.Add(r.Context(), user, name)
if err != nil {
handleError(w, r, err)
return
}
} else {
account, err = h.s.UpdateName(r.Context(), user, id, name)
if err != nil {
handleError(w, r, err)
return
}
}
comp := t.AccountItem(account)
h.r.Render(r, w, comp)
}
}
func (h AccountImpl) handleDeleteAccount() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
updateSpan(r)
user := middleware.GetUser(r)
if user == nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
id := r.PathValue("id")
err := h.s.Delete(r.Context(), user, id)
if err != nil {
handleError(w, r, err)
return
}
}
}