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 441b361
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 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 @@ -159,7 +160,11 @@ func StateReconciler[T Object](obj T, resource schema.GroupVersionResource, name
controller.logger.Error(err, "failed to restructure object", "kind", kind)
return nil
}
runtimeObj, _ := obj.(Object)
runtimeObj, ok := obj.(Object)
if !ok {
controller.logger.Error(fmt.Errorf("unexpected object type: %T", obj), "failed to cast object", "kind", kind)
return nil
}
return runtimeObj
})
},
Expand Down Expand Up @@ -221,16 +226,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
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 441b361

Please sign in to comment.