/
service.go
62 lines (51 loc) · 1.6 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package twilio
import (
"fmt"
"github.com/svilenkomitov/notifire/internal/domain"
"github.com/svilenkomitov/notifire/internal/integration"
"github.com/twilio/twilio-go"
openapi "github.com/twilio/twilio-go/rest/api/v2010"
"regexp"
)
const (
validatePhoneRegex = "((\\+|\\(|0)?\\d{1,3})?((\\s|\\)|\\-))?(\\d{10})$"
)
type service struct {
client *twilio.RestClient
}
func New(config *Config) integration.Service {
return &service{
client: twilio.NewRestClientWithParams(twilio.ClientParams{
Username: config.Domain,
Password: config.ApiKey,
}),
}
}
func (s service) Send(notification domain.Notification) error {
if err := s.Validate(notification); err != nil {
return err
}
_, err := s.client.Api.CreateMessage(&openapi.CreateMessageParams{
From: ¬ification.Sender,
To: ¬ification.Recipient,
Body: ¬ification.Body,
})
return err
}
func (s service) Validate(notification domain.Notification) *integration.ValidationError {
if notification.Channel.ToLower() != domain.SMS {
return integration.NewValidationError(fmt.Sprintf("invalid channel [%s]", notification.Channel))
}
if isValid, _ := regexp.MatchString(validatePhoneRegex, notification.Sender); !isValid {
return integration.NewValidationError(fmt.Sprintf("sender [%s] is not valid",
notification.Sender))
}
if isValid, _ := regexp.MatchString(validatePhoneRegex, notification.Recipient); !isValid {
return integration.NewValidationError(fmt.Sprintf("recipient [%s] is not valid",
notification.Sender))
}
if notification.Body == "" {
return integration.NewValidationError("body cannot be empty")
}
return nil
}