-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
114 lines (92 loc) · 2.49 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package grpc
import (
"context"
"errors"
"fmt"
v1 "github.com/alexfalkowski/konfig/api/konfig/v1"
source "github.com/alexfalkowski/konfig/source/configurator"
serrors "github.com/alexfalkowski/konfig/source/configurator/errors"
"go.uber.org/fx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ServerParams for gRPC.
type ServerParams struct {
fx.In
Configurator source.Configurator
Transformer *source.Transformer
}
// NewServer for gRPC.
func NewServer(params ServerParams) v1.ServiceServer {
return &Server{conf: params.Configurator, transformer: params.Transformer}
}
// Server for gRPC.
type Server struct {
conf source.Configurator
transformer *source.Transformer
v1.UnimplementedServiceServer
}
// GetConfig for gRPC.
func (s *Server) GetConfig(ctx context.Context, req *v1.GetConfigRequest) (*v1.GetConfigResponse, error) {
if req.Continent == "" {
req.Continent = "*"
}
if req.Country == "" {
req.Country = "*"
}
if req.Kind == "" {
req.Kind = "yaml"
}
resp := &v1.GetConfigResponse{
Config: &v1.Config{
Application: req.Application,
Version: req.Version,
Environment: req.Environment,
Continent: req.Continent,
Country: req.Country,
Command: req.Command,
Kind: req.Kind,
},
}
if err := s.validateGetConfigRequest(req); err != nil {
return resp, err
}
p := source.ConfigParams{
Application: req.Application,
Version: req.Version,
Environment: req.Environment,
Continent: req.Continent,
Country: req.Country,
Command: req.Command,
Kind: req.Kind,
}
c, err := s.conf.GetConfig(ctx, p)
if err != nil {
if errors.Is(err, serrors.ErrNotFound) {
return resp, status.Error(codes.NotFound, fmt.Sprintf("%s was not found", p))
}
return resp, status.Error(codes.Internal, "could get config")
}
data, err := s.transformer.Transform(ctx, c)
if err != nil {
return resp, status.Error(codes.Internal, "could not transform")
}
resp.Config.Kind = c.Kind
resp.Config.Data = data
return resp, nil
}
func (s *Server) validateGetConfigRequest(req *v1.GetConfigRequest) error {
if req.Application == "" {
return status.Error(codes.InvalidArgument, "invalid application")
}
if req.Version == "" {
return status.Error(codes.InvalidArgument, "invalid version")
}
if req.Environment == "" {
return status.Error(codes.InvalidArgument, "invalid environment")
}
if req.Command == "" {
return status.Error(codes.InvalidArgument, "invalid command")
}
return nil
}