Skip to content

Instantly share code, notes, and snippets.

@kyriediculous
Created May 8, 2019 13:24
Show Gist options
  • Save kyriediculous/7ca525c70eb30331b645d15beb4485a2 to your computer and use it in GitHub Desktop.
Save kyriediculous/7ca525c70eb30331b645d15beb4485a2 to your computer and use it in GitHub Desktop.
func (s *BlogServiceServer) ReadBlog(ctx context.Context, req *blogpb.ReadBlogReq) (*blogpb.ReadBlogRes, error) {
// convert string id (from proto) to mongoDB ObjectId
oid, err := primitive.ObjectIDFromHex(req.GetId())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("Could not convert to ObjectId: %v", err))
}
result := blogdb.FindOne(ctx, bson.M{"_id": oid})
// Create an empty BlogItem to write our decode result to
data := BlogItem{}
// decode and write to data
if err := result.Decode(&data); err != nil {
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find blog with Object Id %s: %v", req.GetId(), err))
}
// Cast to ReadBlogRes type
response := &blogpb.ReadBlogRes{
Blog: &blogpb.Blog{
Id: oid.Hex(),
AuthorId: data.AuthorID,
Title: data.Title,
Content: data.Content,
},
}
return response, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment