groupMember.go 1.24 KB
package group_m

import (
	"gorm.io/gorm"
)

type GroupMember struct {
	GroupId string
	UserId  uint64
}

func (gm *GroupMember) Create(db *gorm.DB) error {
	return db.Create(gm).Error
}

func (gm *GroupMember) Remove(db *gorm.DB) error {
	return db.Where(gm).Delete(&GroupMember{}).Error
}

func (gm *GroupMember) Find(db *gorm.DB) ([]GroupMember, error) {
	rows := make([]GroupMember, 0)
	if err := db.Where(gm).Order("created_time DESC").Find(&rows).Error; err != nil {
		return nil, err
	}
	return rows, nil
}

func GetMembers(db *gorm.DB, groupId string) ([]GroupMember, error) {
	gm := GroupMember{
		GroupId: groupId,
	}
	return gm.Find(db)
}

func GetMemberCount(db *gorm.DB, groupId string) (uint, error) {
	gm := GroupMember{
		GroupId: groupId,
	}
	var c int64
	if err := db.Model(&GroupMember{}).Where(&gm).Count(&c).Error; err != nil {
		return 0, err
	}
	return uint(c), nil
}

func GetJoinedGroups(db *gorm.DB, userId uint64) ([]GroupMember, error) {
	gm := GroupMember{
		UserId: userId,
	}
	return gm.Find(db)
}

func IsGroupMember(db *gorm.DB, groupId string, userId uint64) (bool, error) {
	gm := GroupMember{
		GroupId: groupId,
		UserId:  userId,
	}
	rows, err := gm.Find(db)
	if err != nil {
		return false, err
	}
	return len(rows) > 0, nil
}