leaf-library-3/internal/services/collection/collection.go
2024-12-10 18:22:14 +08:00

80 lines
2.0 KiB
Go

package collection
import (
"context"
"leafdev.top/Leaf/leaf-library-3/internal/errs"
"leafdev.top/Leaf/leaf-library-3/internal/dto"
"leafdev.top/Leaf/leaf-library-3/internal/entity"
)
func (s *Service) Get(ctx context.Context, collectionId dto.EntityId) (*entity.Collection, error) {
exists, err := s.Exists(ctx, collectionId)
if err != nil {
return nil, err
}
if !exists {
return nil, errs.ErrCollectionNotExists
}
return s.dao.WithContext(ctx).Collection.Where(s.dao.Collection.ID.Eq(collectionId.Uint())).First()
}
func (s *Service) Exists(ctx context.Context, CollectionId dto.EntityId) (bool, error) {
num, err := s.dao.WithContext(ctx).Collection.Where(s.dao.Collection.ID.Eq(CollectionId.Uint())).Count()
return num > 0, err
}
func (s *Service) List(ctx context.Context, workspaceId dto.EntityId) ([]*entity.Collection, error) {
return s.dao.WithContext(ctx).Collection.Where(s.dao.Collection.WorkspaceId.Eq(workspaceId.Uint())).Find()
}
func (s *Service) Create(ctx context.Context, workspaceId dto.EntityId, name string) (*entity.Collection, error) {
var collection = &entity.Collection{
Name: name,
WorkspaceId: workspaceId,
}
err := s.dao.WithContext(ctx).Collection.Create(collection)
if err != nil {
return nil, err
}
return collection, nil
}
func (s *Service) Update(ctx context.Context, collectionId dto.EntityId, name string) (*entity.Collection, error) {
collection, err := s.Get(ctx, collectionId)
if err != nil {
return nil, err
}
collection.Name = name
err = s.dao.WithContext(ctx).Collection.Save(collection)
if err != nil {
return nil, err
}
return collection, nil
}
func (s *Service) Delete(ctx context.Context, collectionId dto.EntityId) error {
exists, err := s.Exists(ctx, collectionId)
if err != nil {
return err
}
if !exists {
return errs.ErrCollectionNotExists
}
// 使用软删除
_, err = s.dao.WithContext(ctx).Collection.Where(s.dao.Collection.ID.Eq(collectionId.Uint())).Delete()
return err
}