Skip to content

Commit 9dc8124

Browse files
authored
Introduce maputil (#919)
* introduce maputil * add GetMapOptional * linting * linting 2
1 parent 40000d2 commit 9dc8124

File tree

2 files changed

+435
-0
lines changed

2 files changed

+435
-0
lines changed

data/utils/maputil/maputil.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package maputil
2+
3+
import "fmt"
4+
5+
func GetMap(obj map[string]any, key string) (map[string]any, error) {
6+
if untypedValue, ok := obj[key]; ok {
7+
if value, ok := untypedValue.(map[string]any); ok {
8+
return value, nil
9+
}
10+
err := fmt.Errorf("the field '%s' should be an object", key)
11+
return nil, err
12+
}
13+
14+
err := fmt.Errorf("the field '%s' should be set", key)
15+
return nil, err
16+
}
17+
18+
func GetMapOptional(obj map[string]any, key string) (map[string]any, error) {
19+
if untypedValue, ok := obj[key]; ok {
20+
if value, ok := untypedValue.(map[string]any); ok {
21+
return value, nil
22+
}
23+
err := fmt.Errorf("the field '%s' should be an object", key)
24+
return nil, err
25+
}
26+
27+
// Value optional, not error
28+
return nil, nil
29+
}
30+
31+
func GetBool(obj map[string]any, key string) (bool, error) {
32+
if untypedValue, ok := obj[key]; ok {
33+
if value, ok := untypedValue.(bool); ok {
34+
return value, nil
35+
}
36+
err := fmt.Errorf("the field '%s' should be a bool", key)
37+
return false, err
38+
}
39+
40+
err := fmt.Errorf("the field '%s' should be set", key)
41+
return false, err
42+
}
43+
44+
func GetBoolOptional(obj map[string]any, key string) (bool, error) {
45+
if untypedValue, ok := obj[key]; ok {
46+
if value, ok := untypedValue.(bool); ok {
47+
return value, nil
48+
}
49+
err := fmt.Errorf("the field '%s' should be a bool", key)
50+
return false, err
51+
}
52+
53+
// Value optional, not error
54+
return false, nil
55+
}
56+
57+
func GetString(obj map[string]any, key string) (string, error) {
58+
if untypedValue, ok := obj[key]; ok {
59+
if value, ok := untypedValue.(string); ok {
60+
return value, nil
61+
}
62+
err := fmt.Errorf("the field '%s' should be a string", key)
63+
return "", err
64+
}
65+
66+
err := fmt.Errorf("the field '%s' should be set", key)
67+
return "", err
68+
}
69+
70+
func GetStringOptional(obj map[string]any, key string) (string, error) {
71+
if untypedValue, ok := obj[key]; ok {
72+
if value, ok := untypedValue.(string); ok {
73+
return value, nil
74+
}
75+
err := fmt.Errorf("the field '%s' should be a string", key)
76+
return "", err
77+
}
78+
79+
// Value optional, not error
80+
return "", nil
81+
}

0 commit comments

Comments
 (0)