-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgapi.go
69 lines (53 loc) · 1.85 KB
/
gapi.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
package main
import (
"context"
"grpc-gateway-example/gen/go/todo/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
func NewServer(db Database) *Server {
return &Server{
Database: db,
}
}
type Server struct {
todo.UnimplementedYourServiceServer
Database
}
// GetAllTODO implements todo.YourServiceServer.
func (s *Server) GetAllTODO(ctx context.Context, req *todo.IDRequest) (*todo.RepeatedStringMessage, error) {
val, err := s.Database.FindAll(ctx)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get todo: %v", err)
}
return &todo.RepeatedStringMessage{Value: val}, nil
}
func (s *Server) CreateTODO(ctx context.Context, val *todo.StringMessage) (*todo.StringMessage, error) {
err := s.Database.Create(ctx, val.Value)
return &todo.StringMessage{Value: val.Value}, err
}
func (s *Server) UpdateTODO(ctx context.Context, val *todo.StringMessage) (*todo.StringMessage, error) {
if val.Id == nil {
return nil, status.Errorf(codes.InvalidArgument, "missing ID in request")
}
err := s.Database.Update(ctx, Int32ToIntP(*val.Id), val.Value)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to update todo: %v", err)
}
return &todo.StringMessage{Value: val.Value}, nil
}
func (s *Server) GetTODO(ctx context.Context, val *todo.IDRequest) (*todo.StringMessage, error) {
data, err := s.Database.Find(ctx, int(val.Id))
if err != nil {
return nil, status.Errorf(codes.NotFound, "failed to get todo: %v", err)
}
return &todo.StringMessage{Value: data}, nil
}
func (s *Server) DeleteTODO(ctx context.Context, val *todo.IDRequest) (*todo.StringMessage, error) {
err := s.Database.Delete(ctx, int(val.Id))
if err != nil {
return nil, status.Errorf(codes.NotFound, "failed to delete todo: %v", err)
}
return &todo.StringMessage{Value: "deleted"}, nil
}
var _ todo.YourServiceServer = (*Server)(nil)