[FEATURE] Request Validation via GrpcValidator Annotation and Custom Validators #1176
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request introduces a structured solution for handling request validation in a gRPC service. The solution involves decoupling the validation logic from the business logic layer to ensure that requests are validated before reaching the service layer. The key components of this solution include a custom annotation, a validator discovery mechanism, and a base validator.
Key Features:
GrpcValidator Annotation:
The GrpcValidator annotation associates a gRPC method with a specific request class and its corresponding validator.
It allows specifying the validator class and the validation method to be invoked for that request type.
This separation allows for clean and maintainable code by keeping validation logic isolated from the business logic of the service.
Example Usage:
@GrpcValidator(requestClass = MyRequest.class, validatorClass = MyRequestValidator.class, validatorMethod = "validateRequest")
public void myGrpcMethod(MyRequest request) {
// gRPC method implementation
}
GrpcValidatorDiscoverer:
This component is responsible for scanning the application during server startup to discover all the GrpcValidator annotations.
It registers the relationship between request classes and their corresponding validation methods, storing them for easy lookup at runtime. This enables dynamic invocation of custom validation methods for each request type.
Base Validator:
A base class that handles common validation tasks such as checking for required fields, regex pattern matching, and other basic validation rules. For custom validation, the base validator invokes the appropriate validation method discovered by the GrpcValidatorDiscoverer.
Flow:
Benefits: