Core

/app/util/mapparsearray.go (2.0 KB)

 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
82
83
84
85
86
package util

import (
"fmt"
"strings"

"github.com/pkg/errors"
"github.com/samber/lo"
)

func (m ValueMap) ParseArray(path string, allowMissing bool, allowEmpty bool) ([]any, error) {
result, err := m.GetPath(path, allowMissing)
if err != nil {
return nil, errors.Wrap(err, "invalid array")
}
switch t := result.(type) {
case string:
if strings.TrimSpace(t) == "" {
return nil, nil
}
var ret []any
err := FromJSON([]byte(t), &ret)
if err != nil {
return nil, decorateError(m, path, "time", errors.Wrap(err, "invalid JSON"))
}
return ret, err
case []byte:
if len(t) == 0 {
return nil, nil
}
var ret []any
err := FromJSON(t, &ret)
if err != nil {
return nil, decorateError(m, path, "time", errors.Wrap(err, "invalid JSON"))
}
return ret, err
case []any:
if (!allowEmpty) && len(t) == 0 {
return nil, errors.New("empty array")
}
return t, nil
case []string:
if (!allowEmpty) && len(t) == 0 {
return nil, errors.New("empty array")
}
return InterfaceArrayFrom(t...), nil
case []int:
if (!allowEmpty) && len(t) == 0 {
return nil, errors.New("empty array")
}
return InterfaceArrayFrom(t...), nil
case nil:
if !allowEmpty {
return nil, errors.Errorf("could not find array for path [%s]", path)
}
return nil, nil
default:
return nil, invalidTypeError(path, "array", t)
}
}

func (m ValueMap) ParseArrayInt(path string, allowMissing bool, allowEmpty bool) ([]int, error) {
a, err := m.ParseArray(path, allowMissing, allowEmpty)
if err != nil {
return nil, err
}
ia := make([]int, 0, len(a))
for idx, x := range a {
i, err := valueInt(fmt.Sprintf("%s.%d", path, idx), x, allowEmpty)
if err != nil {
return nil, err
}
ia = append(ia, i)
}
return ia, nil
}

func (m ValueMap) ParseArrayString(path string, allowMissing bool, allowEmpty bool) ([]string, error) {
a, err := m.ParseArray(path, allowMissing, allowEmpty)
if err != nil {
return nil, err
}
return lo.Map(a, func(x any, _ int) string {
return fmt.Sprint(x)
}), nil
}