116 lines
2.5 KiB
Go
116 lines
2.5 KiB
Go
package route
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"forge.cadoles.com/Cadoles/fake-sms/internal/command"
|
|
"forge.cadoles.com/Cadoles/fake-sms/internal/model"
|
|
"forge.cadoles.com/Cadoles/fake-sms/internal/query"
|
|
"forge.cadoles.com/Cadoles/fake-sms/internal/storm"
|
|
"github.com/go-chi/chi"
|
|
"github.com/pkg/errors"
|
|
"gitlab.com/wpetit/goweb/cqrs"
|
|
"gitlab.com/wpetit/goweb/middleware/container"
|
|
"gitlab.com/wpetit/goweb/service/template"
|
|
)
|
|
|
|
func serveSMSPage(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()
|
|
|
|
sms, 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"))
|
|
}
|
|
|
|
ctn := container.Must(ctx)
|
|
tmpl := template.Must(ctn)
|
|
|
|
data := extendTemplateData(w, r, template.Data{
|
|
"SMS": sms,
|
|
})
|
|
|
|
if err := tmpl.RenderPage(w, "sms.html.tmpl", data); err != nil {
|
|
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
|
}
|
|
}
|
|
|
|
func handleSMSDelete(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()
|
|
ctn := container.Must(ctx)
|
|
bus := cqrs.Must(ctn)
|
|
|
|
deleteSMS := &command.DeleteSMSRequest{
|
|
SMSID: smsID,
|
|
}
|
|
|
|
if _, err := bus.Exec(ctx, deleteSMS); err != nil {
|
|
panic(errors.Wrap(err, "could not delete email"))
|
|
}
|
|
|
|
http.Error(w, http.StatusText(http.StatusNoContent), http.StatusNoContent)
|
|
}
|
|
|
|
func getSMSID(r *http.Request) (int, error) {
|
|
rawSMSID := chi.URLParam(r, "id")
|
|
|
|
smsID, err := strconv.ParseInt(rawSMSID, 10, 32)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return int(smsID), nil
|
|
}
|
|
|
|
func openSMS(ctx context.Context, emailID int) (*model.SMS, error) {
|
|
ctn := container.Must(ctx)
|
|
bus := cqrs.Must(ctn)
|
|
req := &query.OpenSMSRequest{
|
|
SMSID: emailID,
|
|
}
|
|
|
|
result, err := bus.Query(ctx, req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
openEmailData, ok := result.Data().(*query.OpenSMSData)
|
|
if !ok {
|
|
return nil, errors.New("unexpected result data")
|
|
}
|
|
|
|
return openEmailData.SMS, nil
|
|
}
|
|
|
|
func getAttachmentIndex(r *http.Request) (int, error) {
|
|
rawAttachmendIndex := chi.URLParam(r, "attachmendIndex")
|
|
|
|
attachmendIndex, err := strconv.ParseInt(rawAttachmendIndex, 10, 32)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return int(attachmendIndex), nil
|
|
}
|