Files
aeternalis/server/internal/transport/housing.go
T

68 lines
1.6 KiB
Go

package transport
import (
"aeternalis/server/internal/store"
"errors"
"net/http"
)
func (h *HTTP) housingRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/housing", func(w http.ResponseWriter, r *http.Request) {
account, e := h.auth.account(r)
if e != nil {
fail(w, 401, "sign in required")
return
}
h.s.mu.Lock()
defer h.s.mu.Unlock()
if !h.s.ready.Load() {
fail(w, 503, "world unavailable")
return
}
state, e := h.auth.db.HouseState(r.Context(), h.s.world, account)
if e != nil {
h.housingFailure(w, e)
return
}
respond(w, 200, state)
})
mux.HandleFunc("POST /api/housing", func(w http.ResponseWriter, r *http.Request) {
account, e := h.auth.account(r)
if e != nil {
fail(w, 401, "sign in required")
return
}
var req store.HouseRequest
if decode(w, r, &req) != nil {
fail(w, 400, "invalid housing request")
return
}
h.s.mu.Lock()
defer h.s.mu.Unlock()
if !h.s.ready.Load() {
fail(w, 503, "world unavailable")
return
}
if e = h.s.persist(r.Context(), ""); e != nil {
fail(w, 503, "save unavailable")
return
}
if e = h.s.lease.HouseAction(r.Context(), h.s.world, account, req); e != nil {
h.housingFailure(w, e)
return
}
respond(w, 200, map[string]bool{"saved": true})
})
}
func (h *HTTP) housingFailure(w http.ResponseWriter, e error) {
if errors.Is(e, store.ErrHousing) || errors.Is(e, store.ErrLivingCharacter) {
fail(w, 409, e.Error())
return
}
h.s.ready.Store(false)
for _, p := range h.s.peers {
p.close()
}
fail(w, 503, "housing save unavailable; reconnect to check the result")
}