forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
81 lines (69 loc) · 1.97 KB
/
utils.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
79
80
81
package legacy
import (
"encoding/json"
"fmt"
"github.com/nyaruka/goflow/utils"
)
// Translations is an inline translation map used for localization
type Translations map[utils.Language]string
// Base looks up the translation in the given base language, or "base"
func (t Translations) Base(baseLanguage utils.Language) string {
val, exists := t[baseLanguage]
if exists {
return val
}
return t["base"]
}
// UnmarshalJSON unmarshals legacy translations from the given JSON
func (t *Translations) UnmarshalJSON(data []byte) error {
// sometimes legacy flows have a single string instead of a map
if data[0] == '"' {
var asString string
if err := json.Unmarshal(data, &asString); err != nil {
return err
}
*t = Translations{"base": asString}
return nil
}
asMap := make(map[utils.Language]string)
if err := json.Unmarshal(data, &asMap); err != nil {
return err
}
*t = asMap
return nil
}
// StringOrNumber represents something we need to read as a string, but might actually be number value in the JSON source
type StringOrNumber string
// UnmarshalJSON unmarshals this from the given JSON
func (s *StringOrNumber) UnmarshalJSON(data []byte) error {
c := data[0]
if c == '"' {
// data is a quoted string
*s = StringOrNumber(data[1 : len(data)-1])
} else if (c >= '0' && c <= '9') || c == '-' {
// data is JSON number
*s = StringOrNumber(data)
} else {
return fmt.Errorf("expected string or number, not %s", string(c))
}
return nil
}
// TypedEnvelope represents a json blob with a type property
type TypedEnvelope struct {
Type string `json:"type" validate:"required"`
Data []byte `json:"-"`
}
type typeOnly struct {
Type string `json:"type" validate:"required"`
}
// UnmarshalJSON unmarshals a typed envelope from the given JSON
func (e *TypedEnvelope) UnmarshalJSON(b []byte) error {
t := &typeOnly{}
if err := utils.UnmarshalAndValidate(b, t); err != nil {
return err
}
e.Type = t.Type
e.Data = make([]byte, len(b))
copy(e.Data, b)
return nil
}