Skip to content

Commit 21637f3

Browse files
author
Ivan De Marino
committed
Use explicit .Type() interrogation instead of reflection to validate type
1 parent 00d6c85 commit 21637f3

File tree

2 files changed

+26
-20
lines changed

2 files changed

+26
-20
lines changed

float64validator/type_validation.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,28 @@ package float64validator
33
import (
44
"context"
55

6+
"github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag"
67
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
78
"github.com/hashicorp/terraform-plugin-framework/types"
89
)
910

1011
// validateFloat ensures that the request contains a Float64 value.
1112
func validateFloat(ctx context.Context, request tfsdk.ValidateAttributeRequest, response *tfsdk.ValidateAttributeResponse) (float64, bool) {
12-
var n types.Float64
13-
14-
diags := tfsdk.ValueAs(ctx, request.AttributeConfig, &n)
15-
16-
if diags.HasError() {
17-
response.Diagnostics = append(response.Diagnostics, diags...)
18-
19-
return 0, false
13+
t := request.AttributeConfig.Type(ctx)
14+
if t != types.Float64Type {
15+
response.Diagnostics.Append(validatordiag.InvalidTypeDiagnostic(
16+
request.AttributePath,
17+
"Expected value of type float64",
18+
t.String(),
19+
))
20+
return 0.0, false
2021
}
2122

22-
if n.Unknown || n.Null {
23-
return 0, false
23+
f := request.AttributeConfig.(types.Float64)
24+
25+
if f.Unknown || f.Null {
26+
return 0.0, false
2427
}
2528

26-
return n.Value, true
29+
return f.Value, true
2730
}

int64validator/type_validation.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,28 @@ package int64validator
33
import (
44
"context"
55

6+
"github.com/hashicorp/terraform-plugin-framework-validators/helpers/validatordiag"
67
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
78
"github.com/hashicorp/terraform-plugin-framework/types"
89
)
910

1011
// validateInt ensures that the request contains an Int64 value.
1112
func validateInt(ctx context.Context, request tfsdk.ValidateAttributeRequest, response *tfsdk.ValidateAttributeResponse) (int64, bool) {
12-
var n types.Int64
13-
14-
diags := tfsdk.ValueAs(ctx, request.AttributeConfig, &n)
15-
16-
if diags.HasError() {
17-
response.Diagnostics = append(response.Diagnostics, diags...)
18-
13+
t := request.AttributeConfig.Type(ctx)
14+
if t != types.Int64Type {
15+
response.Diagnostics.Append(validatordiag.InvalidTypeDiagnostic(
16+
request.AttributePath,
17+
"Expected value of type int64",
18+
t.String(),
19+
))
1920
return 0, false
2021
}
2122

22-
if n.Unknown || n.Null {
23+
i := request.AttributeConfig.(types.Int64)
24+
25+
if i.Unknown || i.Null {
2326
return 0, false
2427
}
2528

26-
return n.Value, true
29+
return i.Value, true
2730
}

0 commit comments

Comments
 (0)