I’m writing a module that defines a resource type. The resource has two config fields (let’s call them fieldA
and fieldB
), and the requirement is that no two resources of that type can share the same combination of those values.
To enforce this, I’m registering a validator with the resource type:
public static final ResourceType RESOURCE_TYPE =
new ResourceType(MODULE_ID, RESOURCE_ID_MY_RESOURCE);
public static final ResourceTypeMeta<MyResource> META =
ResourceTypeMeta.newBuilder(MyResource.class)
.resourceType(RESOURCE_TYPE)
.categoryName("My Settings")
.withValidator(new MyResourceValidator());
The validator looks something like this:
private static class MyResourceValidator implements ResourceValidator<MyResource> {
@Override
public Optional<ValidationErrors> validate(MyResource resource) {
// check if (fieldA, fieldB) combo is unique among
// all resources of type MyResource
}
}
The issue is that in the validate
method I only get the config object (MyResource
). I don’t get the resource’s metadata, such as name or enabled. That makes it tricky to enforce uniqueness, because:
-
When updating a resource, my check sees it as a duplicate of itself.
-
When fetching the resources with a GET, validation runs for each resource, and each one flags itself as a duplicate. This causes the response to include a JSON list of resources with metadata, but none of them have a
config
field populated.
If I had the resource’s name, I could skip the current one during validation, but since I don’t, every check ends up failing.
Is there a way to access the resource’s name from within validate
, or is uniqueness supposed to be enforced somewhere else in the API? If the latter, what’s the correct way to do it? Is there another lifecycle hook I can use that fires before the resource is created and will still communicate a failed validation check back to the user like the validate
method does?