memos/api/v2/resource_service.go

81 lines
2.3 KiB
Go
Raw Normal View History

2023-09-15 19:11:07 +03:00
package v2
import (
"context"
2023-09-16 06:48:53 +03:00
"time"
2023-09-15 19:11:07 +03:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
2023-09-16 06:48:53 +03:00
"google.golang.org/protobuf/types/known/timestamppb"
2023-09-17 17:55:13 +03:00
apiv2pb "github.com/usememos/memos/proto/gen/api/v2"
"github.com/usememos/memos/store"
2023-09-15 19:11:07 +03:00
)
type ResourceService struct {
apiv2pb.UnimplementedResourceServiceServer
Store *store.Store
}
// NewResourceService creates a new ResourceService.
func NewResourceService(store *store.Store) *ResourceService {
return &ResourceService{
Store: store,
}
}
func (s *ResourceService) ListResources(ctx context.Context, _ *apiv2pb.ListResourcesRequest) (*apiv2pb.ListResourcesResponse, error) {
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
}
resources, err := s.Store.ListResources(ctx, &store.FindResource{
CreatorID: &user.ID,
2023-09-15 19:11:07 +03:00
})
if err != nil {
2023-09-19 03:24:24 +03:00
return nil, status.Errorf(codes.Internal, "failed to list resources: %v", err)
2023-09-15 19:11:07 +03:00
}
response := &apiv2pb.ListResourcesResponse{}
for _, resource := range resources {
response.Resources = append(response.Resources, convertResourceFromStore(resource))
}
return response, nil
}
func (s *ResourceService) DeleteResource(ctx context.Context, request *apiv2pb.DeleteResourceRequest) (*apiv2pb.DeleteResourceResponse, error) {
user, err := getCurrentUser(ctx, s.Store)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to get current user: %v", err)
}
resource, err := s.Store.GetResource(ctx, &store.FindResource{
ID: &request.Id,
CreatorID: &user.ID,
})
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to find resource: %v", err)
}
if resource == nil {
return nil, status.Errorf(codes.NotFound, "resource not found")
}
if err := s.Store.DeleteResource(ctx, &store.DeleteResource{
ID: resource.ID,
}); err != nil {
return nil, status.Errorf(codes.Internal, "failed to delete resource: %v", err)
}
return &apiv2pb.DeleteResourceResponse{}, nil
}
2023-09-15 19:11:07 +03:00
func convertResourceFromStore(resource *store.Resource) *apiv2pb.Resource {
return &apiv2pb.Resource{
Id: resource.ID,
CreatedTs: timestamppb.New(time.Unix(resource.CreatedTs, 0)),
Filename: resource.Filename,
ExternalLink: resource.ExternalLink,
Type: resource.Type,
Size: resource.Size,
MemoId: resource.MemoID,
2023-09-15 19:11:07 +03:00
}
}