Skip to content

Commit

Permalink
De/restructure objects via JSON
Browse files Browse the repository at this point in the history
Signed-off-by: Guilherme Cassolato <[email protected]>
  • Loading branch information
guicassolato committed Oct 25, 2024
1 parent ec853f9 commit 2cf0e95
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions controller/runnable.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package controller

import (
"context"
"encoding/json"
"fmt"
"reflect"
"strings"
Expand Down Expand Up @@ -221,16 +222,21 @@ func Restructure[T any](obj any) (any, error) {
if !ok {
return nil, fmt.Errorf("unexpected object type: %T", obj)
}
o := *new(T)
if err := runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredObj.UnstructuredContent(), &o); err != nil {
j, err := unstructuredObj.MarshalJSON()
if err != nil {
return nil, err
}
o := new(T)
if err := json.Unmarshal(j, o); err != nil {
return nil, err
}
return o, nil
}

func Destruct[T any](obj T) (*unstructured.Unstructured, error) {
u, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&obj)
if err != nil {
j, _ := json.Marshal(obj)
var u map[string]interface{}
if err := json.Unmarshal(j, &u); err != nil {
return nil, err
}
return &unstructured.Unstructured{Object: u}, nil
Expand Down

0 comments on commit 2cf0e95

Please sign in to comment.