Skip to content

Commit 0c56ba7

Browse files
authored
Merge pull request #1313 from nyaruka/msgcontent_tweak
Allow `flows.MsgContent` to be unmarshalled from string
2 parents eb81fde + 4437306 commit 0c56ba7

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

flows/msg.go

+12
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,18 @@ func (c *MsgContent) Empty() bool {
250250
return c.Text == "" && len(c.Attachments) == 0 && len(c.QuickReplies) == 0
251251
}
252252

253+
func (c *MsgContent) UnmarshalJSON(d []byte) error {
254+
// if we just have a string we unmarshal it into the text field
255+
if len(d) > 2 && d[0] == '"' && d[len(d)-1] == '"' {
256+
return jsonx.Unmarshal(d, &c.Text)
257+
}
258+
259+
// alias our type so we don't end up here again
260+
type alias MsgContent
261+
262+
return jsonx.Unmarshal(d, (*alias)(c))
263+
}
264+
253265
type BroadcastTranslations map[i18n.Language]*MsgContent
254266

255267
// ForContact is a utility to help callers get the message content for a contact

flows/msg_test.go

+14
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,20 @@ func TestMsgContent(t *testing.T) {
126126
assert.False(t, (&flows.MsgContent{Text: "hi"}).Empty())
127127
assert.False(t, (&flows.MsgContent{Attachments: []utils.Attachment{"image:https://test.jpg"}}).Empty())
128128
assert.False(t, (&flows.MsgContent{QuickReplies: []flows.QuickReply{{Text: "Ok"}}}).Empty())
129+
130+
var c1, c2 flows.MsgContent
131+
132+
// can unmarshal from object
133+
err := json.Unmarshal([]byte(`{"text": "test1", "attachments": ["image:https://test.jpg"]}`), &c1)
134+
assert.NoError(t, err)
135+
assert.Equal(t, "test1", c1.Text)
136+
assert.Equal(t, []utils.Attachment{"image:https://test.jpg"}, c1.Attachments)
137+
138+
// or text
139+
err = json.Unmarshal([]byte(`"test2"`), &c2)
140+
assert.NoError(t, err)
141+
assert.Equal(t, "test2", c2.Text)
142+
assert.Equal(t, []utils.Attachment(nil), c2.Attachments)
129143
}
130144

131145
func TestBroadcastTranslations(t *testing.T) {

0 commit comments

Comments
 (0)