-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
78 lines (61 loc) · 1.23 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package message
import (
"time"
"github.com/WreckingBallStudioLabs/pubsub/common"
"github.com/WreckingBallStudioLabs/pubsub/internal/shared"
"github.com/WreckingBallStudioLabs/pubsub/name"
"github.com/thalesfsp/status"
)
//////
// Const, vars, and types.
//////
// Message definition.
type Message struct {
common.Common
// Data to be published.
Data any `json:"data"`
}
//////
// Methods.
//////
// Process the content of the message `b` into `v`.
func (m *Message) Process(b any, v any) error {
jsonData, err := shared.Marshal(b)
if err != nil {
return err
}
if err := shared.Unmarshal(jsonData, &v); err != nil {
return err
}
return nil
}
//////
// Factory.
//////
// New creates a new message.
func New(topic string, data any) (*Message, error) {
t, err := name.New(topic)
if err != nil {
return nil, err
}
m := &Message{
Common: common.Common{
CreatedAt: time.Now(),
Status: status.Created,
Topic: t.String(),
},
Data: data,
}
if err := shared.Process(m); err != nil {
return nil, err
}
return m, nil
}
// MustNew creates a new message, panicking if there's an error.
func MustNew(topic string, data any) *Message {
m, err := New(topic, data)
if err != nil {
panic(err)
}
return m
}