-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
87 lines (68 loc) · 2.02 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
package grpc
import (
"context"
"fmt"
v1 "github.com/alexfalkowski/bezeichner/api/bezeichner/v1"
"github.com/alexfalkowski/bezeichner/generator"
"github.com/alexfalkowski/bezeichner/mapper"
"go.uber.org/fx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// ServerParams for gRPC.
type ServerParams struct {
fx.In
GeneratorConfig *generator.Config
MapperConfig *mapper.Config
Generators generator.Generators
}
// NewServer for gRPC.
func NewServer(params ServerParams) v1.ServiceServer {
return &Server{generatorConfig: params.GeneratorConfig, mapperConfig: params.MapperConfig, generators: params.Generators}
}
// Server for gRPC.
type Server struct {
generatorConfig *generator.Config
mapperConfig *mapper.Config
generators generator.Generators
v1.UnimplementedServiceServer
}
// GetIdentifiers for gRPC.
func (s *Server) GenerateIdentifiers(ctx context.Context, req *v1.GenerateIdentifiersRequest) (*v1.GenerateIdentifiersResponse, error) {
if req.Count == 0 {
req.Count = 1
}
resp := &v1.GenerateIdentifiersResponse{}
app := s.generatorConfig.Application(req.Application)
if app == nil {
return resp, status.Error(codes.NotFound, fmt.Sprintf("%s: not found", req.Application))
}
g, err := s.generators.Generator(app.Kind)
if err != nil {
return resp, status.Error(codes.NotFound, err.Error())
}
ids := make([]string, req.Count)
for i := 0; i < len(ids); i++ {
id, err := g.Generate(ctx, app.Name)
if err != nil {
return resp, status.Error(codes.Internal, err.Error())
}
ids[i] = app.ID(id)
}
resp.Ids = ids
return resp, nil
}
// MapIdentifiers for gRPC.
func (s *Server) MapIdentifiers(_ context.Context, req *v1.MapIdentifiersRequest) (*v1.MapIdentifiersResponse, error) {
resp := &v1.MapIdentifiersResponse{
Ids: make([]string, len(req.Ids)),
}
for i, id := range req.Ids {
mid, ok := s.mapperConfig.Identifiers[id]
if !ok {
return resp, status.Error(codes.NotFound, fmt.Sprintf("%s: not found", id))
}
resp.Ids[i] = mid
}
return resp, nil
}