pg_role_repository.go 2.8 KB
package repository

import (
	"fmt"
	"github.com/tiptok/gocomm/common"
	. "github.com/tiptok/gocomm/pkg/orm/pgx"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/godevp/pkg/infrastructure/pg/transaction"
)

type RoleRepository struct {
	transactionContext *transaction.TransactionContext
}

func (repository *RoleRepository) Save(dm *domain.Role) (*domain.Role, error) {
	var (
		err error
		m   = &models.Role{}
		tx  = repository.transactionContext.PgTx
	)
	if err = common.GobModelTransform(m, dm); err != nil {
		return nil, err
	}
	if dm.Identify() == nil {
		if err = tx.Insert(m); err != nil {
			return nil, err
		}
		return dm, nil
	}
	if err = tx.Update(m); err != nil {
		return nil, err
	}
	return dm, nil
}

func (repository *RoleRepository) Remove(Role *domain.Role) (*domain.Role, error) {
	var (
		tx        = repository.transactionContext.PgTx
		RoleModel = &models.Role{Id: Role.Identify().(int64)}
	)
	if _, err := tx.Model(RoleModel).Where("id = ?", Role.Id).Delete(); err != nil {
		return Role, err
	}
	return Role, nil
}

func (repository *RoleRepository) FindOne(queryOptions map[string]interface{}) (*domain.Role, error) {
	tx := repository.transactionContext.PgTx
	RoleModel := new(models.Role)
	query := NewQuery(tx.Model(RoleModel), queryOptions)
	query.SetWhere("id = ?", "id")
	if err := query.First(); err != nil {
		return nil, fmt.Errorf("query row not found")
	}
	if RoleModel.Id == 0 {
		return nil, fmt.Errorf("query row not found")
	}
	return repository.transformPgModelToDomainModel(RoleModel)
}

func (repository *RoleRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Role, error) {
	tx := repository.transactionContext.PgTx
	var RoleModels []*models.Role
	Roles := make([]*domain.Role, 0)
	query := NewQuery(tx.Model(&RoleModels), queryOptions).
		SetWhere("parent_id=?", "parentId").
		SetOrder("create_time", "sortByCreateTime").
		SetOrder("update_time", "sortByUpdateTime")
	var err error
	if query.AffectRow, err = query.SelectAndCount(); err != nil {
		return 0, Roles, err
	}
	for _, RoleModel := range RoleModels {
		if Role, err := repository.transformPgModelToDomainModel(RoleModel); err != nil {
			return 0, Roles, err
		} else {
			Roles = append(Roles, Role)
		}
	}
	return int64(query.AffectRow), Roles, nil
}

func (repository *RoleRepository) transformPgModelToDomainModel(RoleModel *models.Role) (*domain.Role, error) {
	m := &domain.Role{}
	err := common.GobModelTransform(m, RoleModel)
	return m, err
}

func NewRoleRepository(transactionContext *transaction.TransactionContext) (*RoleRepository, error) {
	if transactionContext == nil {
		return nil, fmt.Errorf("transactionContext参数不能为nil")
	}
	return &RoleRepository{transactionContext: transactionContext}, nil
}