Skip to content

Commit

Permalink
feat: add join group service
Browse files Browse the repository at this point in the history
  • Loading branch information
wiraphatys committed Jul 4, 2024
1 parent e817ca4 commit f6adf18
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 13 additions & 0 deletions internal/group/group.repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type Repository interface {
DeleteMemberFromGroupWithTX(ctx context.Context, tx *gorm.DB, userUUID, groupUUID uuid.UUID) error
CreateNewGroupWithTX(ctx context.Context, tx *gorm.DB, leaderId string) (*model.Group, error)
JoinGroupWithTX(ctx context.Context, tx *gorm.DB, userUUID, groupUUID uuid.UUID) error
DeleteGroup(ctx context.Context, tx *gorm.DB, groupUUID uuid.UUID) error
}

type repositoryImpl struct {
Expand Down Expand Up @@ -137,3 +138,15 @@ func (r *repositoryImpl) JoinGroupWithTX(ctx context.Context, tx *gorm.DB, userU

return nil
}

func (r *repositoryImpl) DeleteGroup(ctx context.Context, tx *gorm.DB, groupUUID uuid.UUID) error {
result := r.Db.Delete(&model.Group{}, "id = ?", groupUUID)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return errors.New("not found group match with given id")
}

return nil
}
11 changes: 9 additions & 2 deletions internal/group/group.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,10 @@ func (s *serviceImpl) Join(ctx context.Context, in *proto.JoinGroupRequest) (*pr
return nil, err
}

if in.UserId == existedGroup.LeaderID && len(existedGroup.Members) > 1 {
return nil, errors.New("requested user_id is leader of this group so you cannot leave")
}

err = s.repo.WithTransaction(func(tx *gorm.DB) error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Expand All @@ -358,8 +362,11 @@ func (s *serviceImpl) Join(ctx context.Context, in *proto.JoinGroupRequest) (*pr
return err
}

if err := s.repo.DeleteMemberFromGroupWithTX(ctx, tx, userUUID, existedGroup.ID); err != nil {
return err
if in.UserId == existedGroup.LeaderID && len(existedGroup.Members) == 1 {
err := s.repo.DeleteGroup(ctx, tx, existedGroup.ID)
if err != nil {
return err
}
}

return nil
Expand Down

0 comments on commit f6adf18

Please sign in to comment.