all repos

onasty @ 09a22a8

a one-time notes service

onasty/internal/events/mailermq/mailermq.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: mailer service (#55)..., 1 year 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
type Mailer interface {
13
	SendVerificationEmail(ctx context.Context, input SendVerificationEmailRequest) error
14
}
15
16
type MailerMQ struct {
17
	nc *nats.Conn
18
}
19
20
const sendMailSubject = "mailer.send"
21
22
func New(nc *nats.Conn) *MailerMQ {
23
	return &MailerMQ{
24
		nc: nc,
25
	}
26
}
27
28
type sendRequest struct {
29
	RequestID    string            `json:"request_id"`
30
	Receiver     string            `json:"receiver"`
31
	TemplateName string            `json:"template_name"`
32
	Options      map[string]string `json:"options"`
33
}
34
35
type SendVerificationEmailRequest struct {
36
	Receiver string
37
	Token    string
38
}
39
40
func (m MailerMQ) SendVerificationEmail(
41
	ctx context.Context,
42
	inp SendVerificationEmailRequest,
43
) error {
44
	req, err := json.Marshal(sendRequest{
45
		RequestID:    reqid.GetContext(ctx),
46
		Receiver:     inp.Receiver,
47
		TemplateName: "email_verification",
48
		Options: map[string]string{
49
			"token": inp.Token,
50
		},
51
	})
52
	if err != nil {
53
		return err
54
	}
55
56
	resp, err := m.nc.RequestWithContext(ctx, sendMailSubject, req)
57
	if err != nil {
58
		return err
59
	}
60
61
	return events.CheckRespForError(resp)
62
}