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

65 lines
1.4 KiB
Go

package route
import (
"net/http"
"forge.cadoles.com/Cadoles/fake-sms/internal/query"
"forge.cadoles.com/Cadoles/fake-sms/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 browseAPIV1SMS(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
bus := cqrs.Must(ctn)
ctx := r.Context()
getInbox, 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, getInbox)
if err != nil {
panic(errors.Wrap(err, "could not retrieve inbox"))
}
inboxData, ok := result.Data().(*query.OutboxData)
if !ok {
panic(errors.New("unexpected data"))
}
api.DataResponse(w, http.StatusOK, inboxData)
}
func serveAPIV1SMS(w http.ResponseWriter, r *http.Request) {
smsID, err := getSMSID(r)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
ctx := r.Context()
email, err := openSMS(ctx, smsID)
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 sms"))
}
api.DataResponse(w, http.StatusOK, email)
}