pg_message_personal_repository.go 2.3 KB
package repository

import (
	"time"

	pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/pg/models"
)

type MessagePersonalRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

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

func NewMessagePersonalRepository(tx *pgTransaction.TransactionContext) *MessagePersonalRepository {
	return &MessagePersonalRepository{
		transactionContext: tx,
	}
}

func (repo *MessagePersonalRepository) TransformToDomain(param *models.MessagePersonal) *domain.MessagePersonal {
	return &domain.MessagePersonal{
		Id:           param.Id,
		Types:        domain.MessageTypes(param.Types),
		TargetUserId: param.TargetUserId,
		ReadFlag:     domain.MessageReadFlag(param.ReadFlag),
		Title:        param.Title,
		Content:      param.Content,
		CreatedAt:    param.CreatedAt,
		UpdatedAt:    param.UpdatedAt,
		Payload:      param.Payload,
	}
}

func (repo *MessagePersonalRepository) Save(param *domain.MessagePersonal) error {
	message := &models.MessagePersonal{
		Id:           param.Id,
		Types:        string(param.Types),
		TargetUserId: param.TargetUserId,
		ReadFlag:     string(param.ReadFlag),
		Title:        param.Title,
		Content:      param.Content,
		Payload:      param.Payload,
		UpdatedAt:    time.Now(),
		CreatedAt:    param.CreatedAt,
	}
	tx := repo.transactionContext.PgTx
	if message.Id == 0 {
		message.CreatedAt = time.Now()
		_, err := tx.Model(message).Insert()

		return err
	}
	_, err := tx.Model(message).WherePK().Update()
	return err
}

func (repo *MessagePersonalRepository) Find(param map[string]interface{}) (int, []*domain.MessagePersonal, error) {
	tx := repo.transactionContext.PgTx
	var m []*models.MessagePersonal
	query := tx.Model(&m).Limit(20)
	if v, ok := param["targetUserId"]; ok {
		query.Where("target_user_id=?", v)
	}
	if v, ok := param["types"]; ok {
		query.Where("types=?", v)
	}
	if v, ok := param["payload"]; ok {
		query.Where("payload @>?", v)
	}
	query.Order("id desc")
	count, err := query.SelectAndCount()
	if err != nil {
		return 0, nil, err
	}
	var datas []*domain.MessagePersonal
	for _, v := range m {
		d := repo.TransformToDomain(v)
		datas = append(datas, d)
	}
	return count, datas, nil

}