77 lines
2.2 KiB
Go
77 lines
2.2 KiB
Go
package live
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"gorm.io/gorm"
|
|
bizlive "kra/internal/biz/live"
|
|
)
|
|
|
|
type followPO struct {
|
|
ID uint `gorm:"primaryKey"`
|
|
UserID uint `gorm:"not null;uniqueIndex:idx_live_room_follow_user_room"`
|
|
RoomID uint `gorm:"not null;uniqueIndex:idx_live_room_follow_user_room"`
|
|
AnchorUserID uint `gorm:"not null;index"`
|
|
CreatedAt int64 `gorm:"autoCreateTime:milli"`
|
|
}
|
|
|
|
func (followPO) TableName() string { return "live_room_follows" }
|
|
|
|
type followRepo struct{ data Provider }
|
|
|
|
func NewFollowRepo(data Provider) bizlive.FollowRepo { return &followRepo{data: data} }
|
|
|
|
func (r *followRepo) Get(ctx context.Context, userID, roomID uint) (*bizlive.Follow, error) {
|
|
var row followPO
|
|
err := r.db(ctx).Where("user_id = ? AND room_id = ?", userID, roomID).First(&row).Error
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, bizlive.ErrFollowNotFound
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return followToBiz(&row), nil
|
|
}
|
|
|
|
func (r *followRepo) Create(ctx context.Context, item *bizlive.Follow) (*bizlive.Follow, error) {
|
|
var room roomPO
|
|
if err := r.db(ctx).First(&room, item.RoomID).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
|
return nil, bizlive.ErrRoomNotFound
|
|
}
|
|
return nil, err
|
|
}
|
|
item.AnchorUserID = room.AnchorUserID
|
|
po := &followPO{UserID: item.UserID, RoomID: item.RoomID, AnchorUserID: item.AnchorUserID}
|
|
if err := r.db(ctx).Create(po).Error; err != nil {
|
|
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
|
return r.Get(ctx, item.UserID, item.RoomID)
|
|
}
|
|
return nil, err
|
|
}
|
|
return followToBiz(po), nil
|
|
}
|
|
|
|
func (r *followRepo) Delete(ctx context.Context, userID, roomID uint) error {
|
|
result := r.db(ctx).Where("user_id = ? AND room_id = ?", userID, roomID).Delete(&followPO{})
|
|
if result.Error != nil {
|
|
return result.Error
|
|
}
|
|
if result.RowsAffected == 0 {
|
|
return bizlive.ErrFollowNotFound
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (r *followRepo) db(ctx context.Context) *gorm.DB {
|
|
if r == nil || r.data == nil || r.data.DB() == nil {
|
|
return nil
|
|
}
|
|
return r.data.DB().WithContext(ctx)
|
|
}
|
|
|
|
func followToBiz(row *followPO) *bizlive.Follow {
|
|
return &bizlive.Follow{ID: row.ID, UserID: row.UserID, RoomID: row.RoomID, AnchorUserID: row.AnchorUserID}
|
|
}
|