Skip to content

Commit a6c995b

Browse files
committed
Add As method for Object type.
1 parent 95f1e3d commit a6c995b

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

types/object.go

+33
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ package types
22

33
import (
44
"context"
5+
"fmt"
56

67
"github.com/hashicorp/terraform-plugin-framework/attr"
8+
"github.com/hashicorp/terraform-plugin-framework/internal/reflect"
79
"github.com/hashicorp/terraform-plugin-go/tftypes"
810
)
911

@@ -80,6 +82,37 @@ type Object struct {
8082
AttributeTypes map[string]attr.Type
8183
}
8284

85+
// As populates `target` with the data in the Object, throwing an error if the
86+
// data cannot be stored in `target`.
87+
func (o *Object) ElementsAs(ctx context.Context, target interface{}, allowUnhandled bool) error {
88+
// we need a tftypes.Value for this Object to be able to use it with
89+
// our reflection code
90+
values := map[string]tftypes.Value{}
91+
types := map[string]tftypes.Type{}
92+
for key, attr := range o.Attributes {
93+
val, err := attr.ToTerraformValue(ctx)
94+
if err != nil {
95+
return fmt.Errorf("error getting Terraform value for attribute %q: %w", key, err)
96+
}
97+
typ, ok := o.AttributeTypes[key]
98+
if !ok {
99+
return fmt.Errorf("no AttributeType defined for attribute %q: %w", key, err)
100+
}
101+
types[key] = typ.TerraformType(ctx)
102+
err = tftypes.ValidateValue(typ.TerraformType(ctx), val)
103+
if err != nil {
104+
return fmt.Errorf("error using created Terraform value for element %q: %w", key, err)
105+
}
106+
values[key] = tftypes.NewValue(typ.TerraformType(ctx), val)
107+
}
108+
return reflect.Into(ctx, tftypes.NewValue(tftypes.Object{
109+
AttributeTypes: types,
110+
}, values), target, reflect.Options{
111+
UnhandledNullAsEmpty: allowUnhandled,
112+
UnhandledUnknownAsEmpty: allowUnhandled,
113+
})
114+
}
115+
83116
// ToTerraformValue returns the data contained in the AttributeValue as
84117
// a Go type that tftypes.NewValue will accept.
85118
func (o *Object) ToTerraformValue(ctx context.Context) (interface{}, error) {

0 commit comments

Comments
 (0)