forked from kyma-project/kyma
/
labels.go
56 lines (48 loc) · 1.26 KB
/
labels.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
package gqlschema
import (
"encoding/json"
"fmt"
"io"
"github.com/golang/glog"
"github.com/kyma-project/kyma/components/console-backend-service/internal/gqlerror"
"github.com/pkg/errors"
)
type Labels map[string]string
func (y *Labels) UnmarshalGQL(v interface{}) error {
if v == nil {
return nil
}
value, ok := v.(map[string]interface{})
if !ok {
return gqlerror.NewInternal(gqlerror.WithDetails(fmt.Sprintf("unexpected labels type: %T, should be map[string]string", v)))
}
labels, err := y.convertToLabels(value)
if err != nil {
return gqlerror.NewInternal(gqlerror.WithDetails(fmt.Sprintf("while converting labels: %v", err)))
}
*y = labels
return nil
}
func (y Labels) MarshalGQL(w io.Writer) {
bytes, err := json.Marshal(y)
if err != nil {
glog.Error(errors.Wrapf(err, "while marshalling %+v scalar object", y))
return
}
_, err = w.Write(bytes)
if err != nil {
glog.Error(errors.Wrapf(err, "while writing marshalled %+v object", y))
return
}
}
func (y *Labels) convertToLabels(labels map[string]interface{}) (Labels, error) {
result := make(map[string]string)
for k, v := range labels {
val, ok := v.(string)
if !ok {
return nil, errors.Errorf("given value `%v` must be a string", v)
}
result[k] = val
}
return result, nil
}