forked from baron/baron-sso
66 lines
2.3 KiB
Go
66 lines
2.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"baron-sso-backend/internal/domain"
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type TenantGroupRepository interface {
|
|
Create(ctx context.Context, group *domain.TenantGroup) error
|
|
Update(ctx context.Context, group *domain.TenantGroup) error
|
|
Delete(ctx context.Context, id string) error
|
|
FindByID(ctx context.Context, id string) (*domain.TenantGroup, error)
|
|
List(ctx context.Context, limit, offset int) ([]domain.TenantGroup, int64, error)
|
|
AddTenant(ctx context.Context, groupID, tenantID string) error
|
|
RemoveTenant(ctx context.Context, groupID, tenantID string) error
|
|
}
|
|
|
|
type tenantGroupRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewTenantGroupRepository(db *gorm.DB) TenantGroupRepository {
|
|
return &tenantGroupRepository{db: db}
|
|
}
|
|
|
|
func (r *tenantGroupRepository) Create(ctx context.Context, group *domain.TenantGroup) error {
|
|
return r.db.WithContext(ctx).Create(group).Error
|
|
}
|
|
|
|
func (r *tenantGroupRepository) Update(ctx context.Context, group *domain.TenantGroup) error {
|
|
return r.db.WithContext(ctx).Save(group).Error
|
|
}
|
|
|
|
func (r *tenantGroupRepository) Delete(ctx context.Context, id string) error {
|
|
return r.db.WithContext(ctx).Delete(&domain.TenantGroup{}, "id = ?", id).Error
|
|
}
|
|
|
|
func (r *tenantGroupRepository) FindByID(ctx context.Context, id string) (*domain.TenantGroup, error) {
|
|
var group domain.TenantGroup
|
|
if err := r.db.WithContext(ctx).Preload("Tenants").First(&group, "id = ?", id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &group, nil
|
|
}
|
|
|
|
func (r *tenantGroupRepository) List(ctx context.Context, limit, offset int) ([]domain.TenantGroup, int64, error) {
|
|
var groups []domain.TenantGroup
|
|
var total int64
|
|
db := r.db.WithContext(ctx).Model(&domain.TenantGroup{})
|
|
db.Count(&total)
|
|
if err := db.Limit(limit).Offset(offset).Find(&groups).Error; err != nil {
|
|
return nil, 0, err
|
|
}
|
|
return groups, total, nil
|
|
}
|
|
|
|
func (r *tenantGroupRepository) AddTenant(ctx context.Context, groupID, tenantID string) error {
|
|
return r.db.WithContext(ctx).Model(&domain.Tenant{}).Where("id = ?", tenantID).Update("tenant_group_id", groupID).Error
|
|
}
|
|
|
|
func (r *tenantGroupRepository) RemoveTenant(ctx context.Context, groupID, tenantID string) error {
|
|
return r.db.WithContext(ctx).Model(&domain.Tenant{}).Where("id = ? AND tenant_group_id = ?", tenantID, groupID).Update("tenant_group_id", nil).Error
|
|
}
|