pg_received_message_repository.go 1.6 KB
package repository

import (
	"time"

	"github.com/go-pg/pg/v10"
	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 ReceivedMessageRepository struct {
	transactionContext *pgTransaction.TransactionContext
}

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

func NewReceivedMessageRepository(tx *pgTransaction.TransactionContext) *ReceivedMessageRepository {
	return &ReceivedMessageRepository{
		transactionContext: tx,
	}
}

func (repo *ReceivedMessageRepository) SaveMessage(param *domain.ReceivedMessage) error {
	message := &models.ReceivedMessage{
		MessageId:   param.MessageId,
		MessageType: param.MessageType,
		MessageBody: param.MessageBody,
		OccurredOn:  param.OccurredOn,
		CreatedAt:   time.Now(),
	}
	tx := repo.transactionContext.PgTx
	_, err := tx.Model(message).
		Insert()
	return err
}

func (repo *ReceivedMessageRepository) FindMessage(messageId int64) (*domain.ReceivedMessage, error) {
	tx := repo.transactionContext.PgTx
	receivedMessageModel := new(models.ReceivedMessage)
	query := tx.Model(receivedMessageModel).
		Where("message_id = ?", messageId)
	if err := query.First(); err != nil {
		if err != pg.ErrNoRows {
			return nil, err
		}
	}
	message := &domain.ReceivedMessage{
		MessageId:   receivedMessageModel.MessageId,
		MessageType: receivedMessageModel.MessageType,
		MessageBody: receivedMessageModel.MessageBody,
		OccurredOn:  receivedMessageModel.OccurredOn,
		CreatedAt:   receivedMessageModel.CreatedAt,
	}
	return message, nil

}