reaction_service.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package v1
  2. import (
  3. "context"
  4. "fmt"
  5. "google.golang.org/grpc/codes"
  6. "google.golang.org/grpc/status"
  7. "google.golang.org/protobuf/types/known/emptypb"
  8. v1pb "github.com/usememos/memos/proto/gen/api/v1"
  9. "github.com/usememos/memos/store"
  10. )
  11. func (s *APIV1Service) ListMemoReactions(ctx context.Context, request *v1pb.ListMemoReactionsRequest) (*v1pb.ListMemoReactionsResponse, error) {
  12. reactions, err := s.Store.ListReactions(ctx, &store.FindReaction{
  13. ContentID: &request.Name,
  14. })
  15. if err != nil {
  16. return nil, status.Errorf(codes.Internal, "failed to list reactions")
  17. }
  18. response := &v1pb.ListMemoReactionsResponse{
  19. Reactions: []*v1pb.Reaction{},
  20. }
  21. for _, reaction := range reactions {
  22. reactionMessage, err := s.convertReactionFromStore(ctx, reaction)
  23. if err != nil {
  24. return nil, status.Errorf(codes.Internal, "failed to convert reaction")
  25. }
  26. response.Reactions = append(response.Reactions, reactionMessage)
  27. }
  28. return response, nil
  29. }
  30. func (s *APIV1Service) UpsertMemoReaction(ctx context.Context, request *v1pb.UpsertMemoReactionRequest) (*v1pb.Reaction, error) {
  31. user, err := s.GetCurrentUser(ctx)
  32. if err != nil {
  33. return nil, status.Errorf(codes.Internal, "failed to get current user")
  34. }
  35. reaction, err := s.Store.UpsertReaction(ctx, &store.Reaction{
  36. CreatorID: user.ID,
  37. ContentID: request.Reaction.ContentId,
  38. ReactionType: request.Reaction.ReactionType,
  39. })
  40. if err != nil {
  41. return nil, status.Errorf(codes.Internal, "failed to upsert reaction")
  42. }
  43. reactionMessage, err := s.convertReactionFromStore(ctx, reaction)
  44. if err != nil {
  45. return nil, status.Errorf(codes.Internal, "failed to convert reaction")
  46. }
  47. return reactionMessage, nil
  48. }
  49. func (s *APIV1Service) DeleteMemoReaction(ctx context.Context, request *v1pb.DeleteMemoReactionRequest) (*emptypb.Empty, error) {
  50. if err := s.Store.DeleteReaction(ctx, &store.DeleteReaction{
  51. ID: request.Id,
  52. }); err != nil {
  53. return nil, status.Errorf(codes.Internal, "failed to delete reaction")
  54. }
  55. return &emptypb.Empty{}, nil
  56. }
  57. func (s *APIV1Service) convertReactionFromStore(ctx context.Context, reaction *store.Reaction) (*v1pb.Reaction, error) {
  58. creator, err := s.Store.GetUser(ctx, &store.FindUser{
  59. ID: &reaction.CreatorID,
  60. })
  61. if err != nil {
  62. return nil, err
  63. }
  64. return &v1pb.Reaction{
  65. Id: reaction.ID,
  66. Creator: fmt.Sprintf("%s%d", UserNamePrefix, creator.ID),
  67. ContentId: reaction.ContentID,
  68. ReactionType: reaction.ReactionType,
  69. }, nil
  70. }