/
server.go
79 lines (62 loc) · 2.05 KB
/
server.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package subscriber
import (
"context"
"errors"
"net/url"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"gorm.io/gorm"
"github.com/goverland-labs/goverland-core-feed/protocol/feedpb"
)
type SubscriberProvider interface {
GetByID(_ context.Context, id uuid.UUID) (*Subscriber, error)
Create(_ context.Context, webhookURL string) (*Subscriber, error)
Update(_ context.Context, item Subscriber) error
}
type Server struct {
feedpb.UnimplementedSubscriberServer
sp SubscriberProvider
}
func NewServer(sp SubscriberProvider) *Server {
return &Server{
sp: sp,
}
}
func (s *Server) Create(ctx context.Context, req *feedpb.CreateSubscriberRequest) (*feedpb.CreateSubscriberResponse, error) {
if req.GetWebhookUrl() != "" {
if _, err := url.ParseRequestURI(req.GetWebhookUrl()); err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid webhook url")
}
}
sub, err := s.sp.Create(ctx, req.GetWebhookUrl())
if err != nil {
log.Error().Err(err).Msg("create subscriber")
return nil, status.Error(codes.Internal, "internal error")
}
log.Debug().Msgf("create subscriber: %s", sub.ID)
return &feedpb.CreateSubscriberResponse{SubscriberId: sub.ID.String()}, nil
}
func (s *Server) Update(ctx context.Context, req *feedpb.UpdateSubscriberRequest) (*emptypb.Empty, error) {
subID := GetSubscriberID(ctx)
if req.GetWebhookUrl() != "" {
if _, err := url.ParseRequestURI(req.GetWebhookUrl()); err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid webhook url")
}
}
err := s.sp.Update(ctx, Subscriber{
ID: subID,
WebhookURL: req.GetWebhookUrl(),
})
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, status.Error(codes.InvalidArgument, "invalid subscriber ID")
}
if err != nil {
log.Error().Err(err).Msgf("update subscriber: %s", subID)
return nil, status.Error(codes.Internal, "internal error")
}
log.Debug().Msgf("update subscriber: %s", subID)
return &emptypb.Empty{}, nil
}