-
Notifications
You must be signed in to change notification settings - Fork 20
/
connection.go
53 lines (43 loc) · 1.49 KB
/
connection.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
package flows
import (
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/utils/jsonx"
)
// Connection represents a connection to a specific channel using a specific URN
type Connection struct {
channel *assets.ChannelReference
urn urns.URN
}
// NewConnection creates a new connection
func NewConnection(channel *assets.ChannelReference, urn urns.URN) *Connection {
return &Connection{channel: channel, urn: urn}
}
// Channel returns a reference to the channel
func (c *Connection) Channel() *assets.ChannelReference { return c.channel }
// URN returns the URN
func (c *Connection) URN() urns.URN { return c.urn }
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type connectionEnvelope struct {
Channel *assets.ChannelReference `json:"channel" validate:"required,dive"`
URN urns.URN `json:"urn" validate:"required,urn"`
}
// UnmarshalJSON unmarshals a connection from JSON
func (c *Connection) UnmarshalJSON(data []byte) error {
e := &connectionEnvelope{}
if err := jsonx.Unmarshal(data, e); err != nil {
return err
}
c.channel = e.Channel
c.urn = e.URN
return nil
}
// MarshalJSON marshals this connection into JSON
func (c *Connection) MarshalJSON() ([]byte, error) {
return jsonx.Marshal(&connectionEnvelope{
Channel: c.channel,
URN: c.urn,
})
}