fake-smtp/internal/query/get_inbox.go

64 lines
1.2 KiB
Go

package query
import (
"context"
"forge.cadoles.com/wpetit/fake-smtp/internal/model"
"forge.cadoles.com/wpetit/fake-smtp/internal/storm"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cqrs"
"gitlab.com/wpetit/goweb/middleware/container"
)
type GetInboxRequest struct {
OrderBy string
Limit int
Skip int
Reverse bool
}
type InboxData struct {
Emails []*model.Email
}
func HandleGetInbox(ctx context.Context, qry cqrs.Query) (interface{}, error) {
req, ok := qry.Request().(*GetInboxRequest)
if !ok {
return nil, cqrs.ErrUnexpectedRequest
}
ctn, err := container.From(ctx)
if err != nil {
return nil, errors.Wrap(err, "could not retrieve service container")
}
db, err := storm.From(ctn)
if err != nil {
return nil, errors.Wrap(err, "could not retrieve storm service")
}
emails := make([]*model.Email, 0)
query := db.Select()
if req.OrderBy != "" {
query = query.OrderBy(req.OrderBy)
} else {
query = query.OrderBy("SentAt").Reverse()
}
if req.Reverse {
query = query.Reverse()
}
if err := query.Find(&emails); err != nil {
if err == storm.ErrNotFound {
return &InboxData{emails}, nil
}
return nil, errors.Wrap(err, "could not retrieve emails")
}
return &InboxData{emails}, nil
}