fake-sms/internal/route/outbox.go
2020-12-21 15:59:07 +01:00

63 lines
1.5 KiB
Go

package route
import (
"net/http"
"forge.cadoles.com/Cadoles/fake-sms/internal/command"
"forge.cadoles.com/Cadoles/fake-sms/internal/query"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cqrs"
"gitlab.com/wpetit/goweb/logger"
"gitlab.com/wpetit/goweb/middleware/container"
"gitlab.com/wpetit/goweb/service/template"
)
func serveOutboxPage(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
tmpl := template.Must(ctn)
bus := cqrs.Must(ctn)
ctx := r.Context()
getOutbox, err := createOutboxQueryFromRequest(r)
if err != nil {
logger.Error(ctx, "bad request", logger.E(err))
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
result, err := bus.Query(ctx, getOutbox)
if err != nil {
panic(errors.Wrap(err, "could not retrieve outbox"))
}
inboxData, ok := result.Data().(*query.OutboxData)
if !ok {
panic(errors.New("unexpected data"))
}
data := extendTemplateData(w, r, template.Data{
"Messages": inboxData.Messages,
})
if err := tmpl.RenderPage(w, "outbox.html.tmpl", data); err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
}
func handleClearOutbox(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
bus := cqrs.Must(ctn)
clearInbox := &command.ClearOutboxRequest{}
ctx := r.Context()
if _, err := bus.Exec(ctx, clearInbox); err != nil {
panic(errors.Wrap(err, "could not clear outbox"))
}
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
}