pg_im_info_repository.go 2.9 KB
package repository

import (
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/pg/transaction"
	. "gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
)

type ImInfoRepository struct {
	transactionContext *transaction.TransactionContext
}

func (repository *ImInfoRepository) Save(dm *domain.ImInfo) (*domain.ImInfo, error) {
	var (
		err error
		m   = &models.ImInfo{}
		tx  = repository.transactionContext.PgTx
	)
	if err = GobModelTransform(m, dm); err != nil {
		return nil, err
	}
	if dm.Identify() == nil {
		if _, err = tx.Model(m).Returning("id").Insert(m); err != nil {
			return nil, err
		}
		return dm, nil
	}
	if _, err = tx.Model(m).Where("id=?", m.Id).Update(m); err != nil {
		return nil, err
	}
	return dm, nil
}

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

func (repository *ImInfoRepository) FindOne(queryOptions map[string]interface{}) (*domain.ImInfo, error) {
	tx := repository.transactionContext.PgTx
	ImInfoModel := new(models.ImInfo)
	query := NewQuery(tx.Model(ImInfoModel), queryOptions)
	query.SetWhere("id = ?", "id")
	query.SetWhere("user_id = ?", "user_id")
	if err := query.First(); err != nil {
		return nil, domain.QueryNoRow
	}
	if ImInfoModel.Id == 0 {
		return nil, domain.QueryNoRow
	}
	return repository.transformPgModelToDomainModel(ImInfoModel)
}

func (repository *ImInfoRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.ImInfo, error) {
	tx := repository.transactionContext.PgTx
	var ImInfoModels []*models.ImInfo
	ImInfos := make([]*domain.ImInfo, 0)
	query := NewQuery(tx.Model(&ImInfoModels), queryOptions).
		SetOrder("im_info.create_time", "sortByCreateTime").
		SetOrder("im_info.update_time", "sortByUpdateTime")
	var err error
	if query.AffectRow, err = query.SelectAndCount(); err != nil {
		return 0, ImInfos, err
	}
	for _, ImInfoModel := range ImInfoModels {
		if ImInfo, err := repository.transformPgModelToDomainModel(ImInfoModel); err != nil {
			return 0, ImInfos, err
		} else {
			ImInfos = append(ImInfos, ImInfo)
		}
	}
	return int64(query.AffectRow), ImInfos, nil
}

func (repository *ImInfoRepository) transformPgModelToDomainModel(ImInfoModel *models.ImInfo) (*domain.ImInfo, error) {
	m := &domain.ImInfo{}
	err := GobModelTransform(m, ImInfoModel)
	return m, err
}

func NewImInfoRepository(transactionContext *transaction.TransactionContext) (*ImInfoRepository, error) {
	if transactionContext == nil {
		return nil, ERR_EMPTY_TC
	}
	return &ImInfoRepository{transactionContext: transactionContext}, nil
}