61 lines
1.1 KiB
Go
61 lines
1.1 KiB
Go
|
package email
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"git.selly.red/Selly-Modules/natsio"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
SubjectSendEmail = "send_email"
|
||
|
)
|
||
|
|
||
|
// 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
|
||
|
}
|
||
|
|
||
|
func (c *Client) Send(payload Send) (requestID string, err error) {
|
||
|
msg, err := c.natsServer.Request(payload.Subject, toBytes(payload))
|
||
|
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
|
||
|
}
|