avaje / avaje-http

Controller generation for Javalin, Helidon SE.
https://avaje.io/http/
Apache License 2.0
71 stars 13 forks source link

Validation for bean params for controller class @Get method #60

Closed Travisnv closed 3 years ago

Travisnv commented 3 years ago

Hi @rbygrave,

I wonder can we have validation annotation for bean param? I have a look at generated code for javalin and don't see any part for validation despite of having annotation on bean param class.

Thanks, Travis

rbygrave commented 3 years ago

reference docs at: https://avaje.io/http/#bean-validation

The docs are not super clear but there are 3 steps:

  1. Add the maven dependency to avaje-http-hibernate-validator
  2. Add @Valid to the controller (this is probably the step I suspect you are missing?)
  3. Add @Valid and validation annotations to the request bean being posted

Can you check if you have those 3 steps?

Example:

HelloController has the @Valid on it https://github.com/avaje/avaje-http/blob/master/tests/test-javalin/src/main/java/org/example/myapp/web/HelloController.java#L31

HelloForm as @Valid plus the validation annotations https://github.com/avaje/avaje-http/blob/master/tests/test-javalin/src/main/java/org/example/myapp/web/HelloForm.java#L12

The generated code for that route becomes:

    ApiBuilder.post("/hello/saveform", ctx -> {
      ctx.status(201);
      HelloForm helloForm =  new HelloForm(
        ctx.formParam("name"), 
        ctx.formParam("email")
      );
      helloForm.url = ctx.formParam("url");
      helloForm.startDate = toLocalDate(ctx.formParam("startDate"));

      validator.validate(helloForm);
      controller.saveForm(helloForm);
    });

... and noting that the ...$Route now has a dependency on Validator which is passed in on the constructor. So for HelloController$Route we see ...

@Generated("io.dinject.javalin-generator")
@Singleton
public class HelloController$Route implements WebRoutes {

  private final HelloController controller;
  private final Validator validator;

  public HelloController$Route(HelloController controller, Validator validator) {
   this.controller = controller;
   this.validator = validator;
  }

  @Override
  public void registerRoutes() {
    ...
Travisnv commented 3 years ago
  1. pom.xml has required dependency
  2. controller class, I have @Valid
  3. on parameter of controller method, I use @BeanParam on @Get annotated controller method.

generated code for @Get don't have validator part while @Put and @Post do have.

rbygrave commented 3 years ago

@Get don't have validator part while @Put and @Post do have.

Right, so a bug specific to @Get then - cool.