fake-smtp/internal/route/api.go

65 lines
1.4 KiB
Go

package route
import (
"net/http"
"forge.cadoles.com/wpetit/fake-smtp/internal/query"
"forge.cadoles.com/wpetit/fake-smtp/internal/storm"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/api"
"gitlab.com/wpetit/goweb/cqrs"
"gitlab.com/wpetit/goweb/logger"
"gitlab.com/wpetit/goweb/middleware/container"
)
func browseAPIV1Emails(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
bus := cqrs.Must(ctn)
ctx := r.Context()
getInbox, err := createInboxQueryFromRequest(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, getInbox)
if err != nil {
panic(errors.Wrap(err, "could not retrieve inbox"))
}
inboxData, ok := result.Data().(*query.InboxData)
if !ok {
panic(errors.New("unexpected data"))
}
api.DataResponse(w, http.StatusOK, inboxData)
}
func serveAPIV1Email(w http.ResponseWriter, r *http.Request) {
emailID, err := getEmailID(r)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
ctx := r.Context()
email, err := openEmail(ctx, emailID)
if err != nil {
if errors.Is(err, storm.ErrNotFound) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
panic(errors.Wrap(err, "could not open email"))
}
api.DataResponse(w, http.StatusOK, email)
}