pg_admin_permission.go 2.5 KB
package repository

import (
	"errors"
	"fmt"

	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/pg/transaction"
)

type AdminPermissionRepository struct {
	transactionContext *transaction.TransactionContext
}

var (
	_ domain.AdminPermissionRepository = (*AdminPermissionRepository)(nil)
)

func NewAdminPermissionRepository(transactionContext *transaction.TransactionContext) (*AdminPermissionRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	}
	return &AdminPermissionRepository{transactionContext: transactionContext}, nil
}
func (reponsitory AdminPermissionRepository) transformPgModelToDomainModel(permissionModel *models.AdminPermission) (domain.AdminPermission, error) {
	result := domain.AdminPermission{
		Id:       permissionModel.Id,
		ParentId: permissionModel.ParentId,
		Name:     permissionModel.Name,
		Icon:     permissionModel.Icon,
		Code:     permissionModel.Code,
		Sort:     permissionModel.Sort,
	}
	return result, nil
}

func (reponsitory AdminPermissionRepository) Find(queryOptions domain.PermissionFindOption) ([]domain.AdminPermission, error) {
	db := reponsitory.transactionContext.PgDd
	permissionModels := make([]models.AdminPermission, 0)
	query := db.Model(&permissionModels)
	if len(queryOptions.Ids) > 0 {
		query = query.WhereIn("id in (?) ", queryOptions.Ids)
	}
	query = query.Order("sort")
	if err := query.Select(); err != nil {
		return nil, err
	}
	var result []domain.AdminPermission
	for i := range permissionModels {
		v, _ := reponsitory.transformPgModelToDomainModel(&permissionModels[i])
		result = append(result, v)
	}
	return result, nil
}

func (reponsitory AdminPermissionRepository) FindOne(queryOptions domain.PermissionFindOneOption) (domain.AdminPermission, error) {
	db := reponsitory.transactionContext.PgDd
	var permissionModels models.AdminPermission
	var hasCondition bool
	query := db.Model(&permissionModels)
	if len(queryOptions.Code) > 0 {
		hasCondition = true
		query = query.Where("code=?", queryOptions.Code)
	}
	if queryOptions.Id > 0 {
		hasCondition = true
		query = query.Where("id=?", queryOptions.Id)
	}
	var result domain.AdminPermission
	if !hasCondition {
		return result, errors.New("FindOne 必须要有查询条件")
	}

	err := query.First()
	if err != nil {
		return result, err
	}
	result, _ = reponsitory.transformPgModelToDomainModel(&permissionModels)
	return result, nil
}