I need to a) build a custom validator for a set
i have a case where the valid values in a set depend on the value of another attribute in the root. say it’s called resource_type
so if resource_type is A
then my set can contain Banker, Accountant
but if the resource_type is B
then my set can contain Farmer, Plumber, Electrician
and so on.
how do i setup a custom validator that can validate this?
it needs to take in the path to the resource_type attrib
can only be 1 path expression
then retrieve the value of this
then switch on this value and check the provided set values against my known list of allowed values
and b)
write a test that tests the behaviour properly
how do i properly setup a test that mocks the ctx, req and resp inputs and mocks a tf server so i can test my custom validator?
I think you might be able to use this WhenValueAtMustBeSet to do what you need.
If I remember correctly, you pass it a path.Expression
referring to some other attribute, an attr.Value
“trigger value” to check for on that other attribute, and variadic validators you want to apply to this attribute, when the trigger condition is met.
So, you’d use it like this:
Validators: []validator.Set{
apstravalidator.WhenValueAtMustBeSet( // Only perform this validation when...
path.MatchRelative().AtParent().AtName("resource_type"), // the value here...
types.StringValue("A"), // has this value and then...
setvalidator.ValueStringsAre( // check that this attribute...
stringvalidator.OneOf( // is one of these values.
"Banker",
"Accountant",
)
),
),
apstravalidator.WhenValueAtMustBeSet( // Only perform this validation when...
path.MatchRelative().AtParent().AtName("resource_type"), // the value here...
types.StringValue("B"), // has this value and then...
setvalidator.ValueStringsAre( // check that this attribute...
stringvalidator.OneOf( // is one of these values.
"Farmer",
"Plumber",
"Electrician",
)
),
),
}
If that doesn’t work out, you might find some inspiration in there anyway.