onasty/internal/events/mailermq/mailermq.go (view raw)
| 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(ctx context.Context, input SendVerificationEmailRequest) error |
| 16 | SendPasswordResetEmail(ctx context.Context, input SendPasswordResetEmailRequest) error |
| 17 | } |
| 18 | |
| 19 | type MailerMQ struct { |
| 20 | nc *nats.Conn |
| 21 | } |
| 22 | |
| 23 | func New(nc *nats.Conn) *MailerMQ { |
| 24 | return &MailerMQ{ |
| 25 | nc: nc, |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | type sendRequest struct { |
| 30 | RequestID string `json:"request_id"` |
| 31 | Receiver string `json:"receiver"` |
| 32 | TemplateName string `json:"template_name"` |
| 33 | Options map[string]string `json:"options"` |
| 34 | } |
| 35 | |
| 36 | type SendVerificationEmailRequest struct { |
| 37 | Receiver string |
| 38 | Token string |
| 39 | } |
| 40 | |
| 41 | func (m MailerMQ) SendVerificationEmail( |
| 42 | ctx context.Context, |
| 43 | inp SendVerificationEmailRequest, |
| 44 | ) error { |
| 45 | req, err := json.Marshal(sendRequest{ |
| 46 | RequestID: reqid.GetContext(ctx), |
| 47 | Receiver: inp.Receiver, |
| 48 | TemplateName: "email_verification", |
| 49 | Options: map[string]string{ |
| 50 | "token": inp.Token, |
| 51 | }, |
| 52 | }) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | |
| 57 | resp, err := m.nc.RequestWithContext(ctx, sendTopic, req) |
| 58 | if err != nil { |
| 59 | return err |
| 60 | } |
| 61 | |
| 62 | return events.CheckRespForError(resp) |
| 63 | } |
| 64 | |
| 65 | type SendPasswordResetEmailRequest struct { |
| 66 | Receiver string |
| 67 | Token string |
| 68 | } |
| 69 | |
| 70 | func (m MailerMQ) SendPasswordResetEmail( |
| 71 | ctx context.Context, |
| 72 | inp SendPasswordResetEmailRequest, |
| 73 | ) error { |
| 74 | req, err := json.Marshal(sendRequest{ |
| 75 | RequestID: reqid.GetContext(ctx), |
| 76 | Receiver: inp.Receiver, |
| 77 | TemplateName: "reset_password", |
| 78 | Options: map[string]string{ |
| 79 | "token": inp.Token, |
| 80 | }, |
| 81 | }) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | |
| 86 | resp, err := m.nc.RequestWithContext(ctx, sendTopic, req) |
| 87 | if err != nil { |
| 88 | return err |
| 89 | } |
| 90 | |
| 91 | return events.CheckRespForError(resp) |
| 92 | } |