email/email.go

74 lines
1.4 KiB
Go
Raw Normal View History

2022-11-16 07:13:56 +00:00
package email
2022-11-16 04:02:41 +00:00
import (
"encoding/json"
"errors"
"fmt"
"git.selly.red/Selly-Modules/natsio"
)
2022-11-16 07:04:03 +00:00
func getPrefixEmailService(subject string) string {
2022-11-16 07:13:56 +00:00
return fmt.Sprintf("selly.email.%s", subject)
2022-11-16 07:04:03 +00:00
}
2022-11-16 04:02:41 +00:00
const (
2022-11-17 06:52:59 +00:00
SubjectSendEmail = "send_email"
)
const (
KeyCreateSupplierUser = "create_user"
2022-11-16 04:02:41 +00:00
)
2022-11-16 07:04:03 +00:00
// GetEmail ...
func GetEmail() *Client {
return &Client{}
}
2022-11-16 04:02:41 +00:00
// Client ...
type Client struct {
Config Config
natsServer natsio.Server
natsJetStream natsio.JetStream
}
// NewClient ...
func NewClient(cfg Config) (*Client, error) {
if cfg.Nats.URL == "" {
return nil, errors.New("nats url is required")
}
if err := natsio.Connect(cfg.Nats); err != nil {
return nil, fmt.Errorf("nats connect failed: %v", err)
}
c := &Client{
Config: cfg,
natsServer: natsio.GetServer(),
natsJetStream: natsio.GetJetStream(),
}
return c, nil
}
2022-11-16 07:04:03 +00:00
func (c *Client) Send(payload SendPayload) (requestID string, err error) {
2022-11-17 06:52:59 +00:00
msg, err := c.natsServer.Request(getPrefixEmailService(SubjectSendEmail), toBytes(payload))
2022-11-16 04:02:41 +00:00
if err != nil {
return "", err
}
var res struct {
Data Response `json:"data"`
Error string `json:"error"`
}
if err = json.Unmarshal(msg.Data, &res); err != nil {
return "", err
}
if res.Error != "" {
return "", errors.New(res.Error)
}
return res.Data.RequestID, nil
}
func toBytes(data interface{}) []byte {
b, _ := json.Marshal(data)
return b
}