|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "github.com/rs/zerolog" |
| 8 | + res "github.com/swamphacks/core/apps/api/internal/api/response" |
| 9 | + "github.com/swamphacks/core/apps/api/internal/email" |
| 10 | + "github.com/swamphacks/core/apps/api/internal/services" |
| 11 | +) |
| 12 | + |
| 13 | +type EmailHandler struct { |
| 14 | + emailService *services.EmailService |
| 15 | + logger zerolog.Logger |
| 16 | +} |
| 17 | + |
| 18 | +func NewEmailHandler(emailService *services.EmailService, logger zerolog.Logger) *EmailHandler { |
| 19 | + return &EmailHandler{ |
| 20 | + emailService: emailService, |
| 21 | + logger: logger.With().Str("handler", "EmailHandler").Str("component", "email").Logger(), |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +type QueueEmailRequest struct { |
| 26 | + To string `json:"to"` |
| 27 | + From string `json:"from"` |
| 28 | + Body string `json:"body"` |
| 29 | +} |
| 30 | + |
| 31 | +func (h *EmailHandler) QueueEmail(w http.ResponseWriter, r *http.Request) { |
| 32 | + var req QueueEmailRequest |
| 33 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 34 | + res.SendError(w, http.StatusBadRequest, res.NewError("invalid_request", "Could not parse request body")) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + if !email.IsValidEmail(req.To) || !email.IsValidEmail(req.From) { |
| 39 | + res.SendError(w, http.StatusBadRequest, res.NewError("malformed_email", "To and/or From email is malformed or missing")) |
| 40 | + return |
| 41 | + } |
| 42 | + |
| 43 | + if req.Body == "" { |
| 44 | + res.SendError(w, http.StatusBadRequest, res.NewError("missing_body", "Body is missing or is an empty string.")) |
| 45 | + return |
| 46 | + } |
| 47 | + |
| 48 | + taskInfo, err := h.emailService.QueueSendEmail(req.To, req.From, req.Body) |
| 49 | + if err != nil { |
| 50 | + h.logger.Err(err).Msg("Failed to queue email sending from EmailHandler") |
| 51 | + res.SendError(w, http.StatusInternalServerError, res.NewError("internal_err", "The server went kaput while queueing email sending")) |
| 52 | + return |
| 53 | + } |
| 54 | + |
| 55 | + h.logger.Info().Str("TaskID", taskInfo.ID).Str("Task Queue", taskInfo.Queue).Str("Task Type", taskInfo.Type).Msg("Queued Send Email task!") |
| 56 | + |
| 57 | + w.WriteHeader(http.StatusCreated) |
| 58 | +} |
0 commit comments