/
update.go
53 lines (43 loc) · 1009 Bytes
/
update.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
package main
import (
"context"
"log"
pb "github.com/fabiovalinhos/grpc-go/blog/proto"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
)
func (s *Server) UpdateBlog(ctx context.Context, in *pb.Blog) (*emptypb.Empty, error) {
log.Printf("UpdateBlog was invoked with: %v\n", in)
oid, err := primitive.ObjectIDFromHex(in.Id)
if err != nil {
return nil, status.Errorf(
codes.InvalidArgument,
"Cannot parse ID")
}
data := &BlogItem{
AuthorID: in.AuthorId,
Title: in.Title,
Content: in.Content,
}
res, err := collection.UpdateOne(
ctx,
bson.M{"_id": oid},
bson.M{"$set": data},
)
if err != nil {
return nil, status.Errorf(
codes.Internal,
"Could not update",
)
}
if res.MatchedCount == 0 {
return nil, status.Errorf(
codes.NotFound,
"Cannot find blog with id",
)
}
return &emptypb.Empty{}, nil
}