Home > Software engineering >  Is it possible to trigger validations when calling RestController method from outside?
Is it possible to trigger validations when calling RestController method from outside?

Time:09-13

So far I've got an endpoint which goes as follows:

    @PostMapping(path = "/my-endpoint")
    public ResponseEntity<Void> method(@PathVariable("id") String id,
                                       @RequestBody @Valid MyClass<MyType> body) {
        // custom logic in here
        return ResponseEntity.ok().build();
    }

When performing the POST request to that endpoint, the validation when the object is wrong is performed properly and 400: Bad Request is shown.

However, now due to some code circumstances I want to trigger that method from outside the RestController and perform the same validations via a Consumer.

The new code goes as follows:

    @Bean
    public Consumer<Message<String>> consumer(MyController myController) {
       message -> myController.method("sampleId", message); // message here is parsed to the class, so the proper type is sent to the controller method.
    }

And whenever I check for the myController.method call, the code is always 200: OK, no matter what input is sent.

Is there a way to trigger validations not sent through the REST API?

CodePudding user response:

I suggest to move custom logic from controller to a @Service annotated class first.

Then inject validator @Autowired private Validator validator; and trigger validation.

public void myServiceMethod(MyMessage message) {   
  Set<ConstraintViolation<MyMessage>> violations = validator.validate(message);
  if (!violations.isEmpty()) {
    // ...
  }
}

https://www.baeldung.com/spring-service-layer-validation

  • Related