pg_menu_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 MenuRepository struct {
	transactionContext *transaction.TransactionContext
}

func (repository *MenuRepository) Save(dm *domain.Menu) (*domain.Menu, error) {
	var (
		err error
		m   = &models.Menu{}
		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 *MenuRepository) Remove(Menu *domain.Menu) (*domain.Menu, error) {
	var (
		tx        = repository.transactionContext.PgTx
		MenuModel = &models.Menu{Id: Menu.Identify().(int64)}
	)
	if _, err := tx.Model(MenuModel).Where("id = ?", Menu.Id).Delete(); err != nil {
		return Menu, err
	}
	return Menu, nil
}

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

func (repository *MenuRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Menu, error) {
	tx := repository.transactionContext.PgDd
	var MenuModels []*models.Menu
	Menus := make([]*domain.Menu, 0)
	query := NewQuery(tx.Model(&MenuModels), queryOptions).
		SetOrder("create_time", "sortByCreateTime").
		SetOrder("update_time", "sortByUpdateTime")
	var err error
	if query.AffectRow, err = query.SelectAndCount(); err != nil {
		return 0, Menus, err
	}
	for _, MenuModel := range MenuModels {
		if Menu, err := repository.transformPgModelToDomainModel(MenuModel); err != nil {
			return 0, Menus, err
		} else {
			Menus = append(Menus, Menu)
		}
	}
	return int64(query.AffectRow), Menus, nil
}

func (repository *MenuRepository) transformPgModelToDomainModel(MenuModel *models.Menu) (*domain.Menu, error) {
	m := &domain.Menu{}
	err := common.GobModelTransform(m, MenuModel)
	return m, err
}

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