Skip to content
Snippets Groups Projects
message.go 1.42 KiB
Newer Older
package emissionqueue

import (
	"encoding/json"

	"github.com/jackc/pgtype"
	"github.com/m4rw3r/uuid"
)

// Message ...
type Message struct {
	ID         uint              `db:"id"`
	EnvelopeID uuid.UUID         `db:"envelope_id"`
	ProcessID  uuid.UUID         `db:"process_id"`
	RelatedTo  pgtype.TextArray  `db:"related_to"`
	MsgType    string            `db:"msgtype"`
	Content    []byte            `db:"content"`
	Chunks     pgtype.ByteaArray `db:"chunks"`
}

// NewMessage creates a message.
func NewMessage(relatedTo string, msgType string, content []byte) Message {
	m := Message{
		MsgType: msgType,
		Content: content,
	}
	if err := m.RelatedTo.Set([]string{relatedTo}); err != nil {
		panic(err)
	}
	if err := m.Chunks.Set(nil); err != nil {
		panic(err)
	}

	return m
}

func NewChunkedMessage(msgType string, chunks [][]byte) Message {
	m := Message{
		MsgType: msgType,
	}
	if err := m.RelatedTo.Set([]string{}); err != nil {
		panic(err)
	}
	if err := m.Chunks.Set(chunks); err != nil {
		panic(err)
	}

	return m
}

func NewMessageJSON(relatedTo string, msgType string, payload interface{}) (*Message, error) {
	b, err := json.Marshal(payload)
	if err != nil {
		return nil, err
	}
	m := NewMessage(relatedTo, msgType, b)

	return &m, nil
}

func MustNewMessageJSON(relatedTo string, msgType string, payload interface{}) Message {
	m, err := NewMessageJSON(relatedTo, msgType, payload)
	if err != nil {
		panic(err)
	}

	return *m
}