fake-smtp/internal/command/rotate_email.go

45 lines
988 B
Go

package command
import (
"context"
"forge.cadoles.com/Cadoles/fake-smtp/internal/model"
"forge.cadoles.com/Cadoles/fake-smtp/internal/storm"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cqrs"
"gitlab.com/wpetit/goweb/middleware/container"
)
type RotateEmailRequest struct {
MaxEmail int
}
func HandleRotateEmail(ctx context.Context, cmd cqrs.Command) error {
req, ok := cmd.Request().(*RotateEmailRequest)
if !ok {
return cqrs.ErrUnexpectedRequest
}
ctn, err := container.From(ctx)
if err != nil {
return errors.Wrap(err, "could not retrieve service container")
}
db, err := storm.From(ctn)
if err != nil {
return errors.Wrap(err, "could not retrieve storm service")
}
emailCount, err := db.Select().Count(&model.Email{})
if err != nil {
return errors.Wrap(err, "could not count emails")
}
if emailCount >= req.MaxEmail {
var diff = emailCount - (req.MaxEmail - 1)
db.Select().OrderBy("ID").Limit(diff).Delete(&model.Email{})
}
return nil
}