onasty/internal/events/mailermq/mailermq.go (view raw)
Olexandr Smirnov
Olexandr Smirnov
ss2316544@gmail.com docs: add missing code comments (#185)..., 9 months ago
ss2316544@gmail.com docs: add missing code comments (#185)..., 9 months ago
| 1 | package mailermq |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | |
| 7 | "github.com/nats-io/nats.go" |
| 8 | "github.com/olexsmir/onasty/internal/events" |
| 9 | "github.com/olexsmir/onasty/internal/transport/http/reqid" |
| 10 | ) |
| 11 | |
| 12 | const sendTopic = "mailer.send" |
| 13 | |
| 14 | type Mailer interface { |
| 15 | // SendVerificationEmail sends an email with a verification token to the user. |
| 16 | SendVerificationEmail(ctx context.Context, input SendVerificationEmailRequest) error |
| 17 | |
| 18 | // SendPasswordResetEmail sends an email with a password reset token to the user. |
| 19 | SendPasswordResetEmail(ctx context.Context, input SendPasswordResetEmailRequest) error |
| 20 | } |
| 21 | |
| 22 | type MailerMQ struct { |
| 23 | nc *nats.Conn |
| 24 | } |
| 25 | |
| 26 | func New(nc *nats.Conn) *MailerMQ { |
| 27 | return &MailerMQ{ |
| 28 | nc: nc, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | type sendRequest struct { |
| 33 | RequestID string `json:"request_id"` |
| 34 | Receiver string `json:"receiver"` |
| 35 | TemplateName string `json:"template_name"` |
| 36 | Options map[string]string `json:"options"` |
| 37 | } |
| 38 | |
| 39 | type SendVerificationEmailRequest struct { |
| 40 | Receiver string |
| 41 | Token string |
| 42 | } |
| 43 | |
| 44 | func (m MailerMQ) SendVerificationEmail( |
| 45 | ctx context.Context, |
| 46 | inp SendVerificationEmailRequest, |
| 47 | ) error { |
| 48 | req, err := json.Marshal(sendRequest{ |
| 49 | RequestID: reqid.GetContext(ctx), |
| 50 | Receiver: inp.Receiver, |
| 51 | TemplateName: "email_verification", |
| 52 | Options: map[string]string{ |
| 53 | "token": inp.Token, |
| 54 | }, |
| 55 | }) |
| 56 | if err != nil { |
| 57 | return err |
| 58 | } |
| 59 | |
| 60 | resp, err := m.nc.RequestWithContext(ctx, sendTopic, req) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | |
| 65 | return events.CheckRespForError(resp) |
| 66 | } |
| 67 | |
| 68 | type SendPasswordResetEmailRequest struct { |
| 69 | Receiver string |
| 70 | Token string |
| 71 | } |
| 72 | |
| 73 | func (m MailerMQ) SendPasswordResetEmail( |
| 74 | ctx context.Context, |
| 75 | inp SendPasswordResetEmailRequest, |
| 76 | ) error { |
| 77 | req, err := json.Marshal(sendRequest{ |
| 78 | RequestID: reqid.GetContext(ctx), |
| 79 | Receiver: inp.Receiver, |
| 80 | TemplateName: "reset_password", |
| 81 | Options: map[string]string{ |
| 82 | "token": inp.Token, |
| 83 | }, |
| 84 | }) |
| 85 | if err != nil { |
| 86 | return err |
| 87 | } |
| 88 | |
| 89 | resp, err := m.nc.RequestWithContext(ctx, sendTopic, req) |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | return events.CheckRespForError(resp) |
| 95 | } |