turkraft / springfilter

Dynamically filter JPA entities and Mongo collections with a user-friendly query syntax. Seamless integration with Spring APIs. Star to support the project! ⭐️
https://turkraft.com/springfilter
216 stars 35 forks source link

How to set require false in swagger? #381

Closed abccbaandy closed 3 months ago

abccbaandy commented 3 months ago

In this issue https://github.com/turkraft/springfilter/issues/177

List<Entity> listEntities(@Parameter(in = ParameterIn.QUERY, name = "filter", description = "Filter query", schema = @Schema(type = "string")) @Filter Specification<Entity> spec) {
 // ...
}

We can use @Parameter to show correct format in swagger, but even with require = false, it still be required in swagger.

I try with @RequestParam with require false, but it will make the whole filter not work(the filter will be always null).

torshid commented 3 months ago

Not sure I can help with Swagger. The parameter is not required when using @Filter.

abccbaandy commented 3 months ago

@torshid You are right, but I guess @Filter use some special way to generate the Specification right?

And it make swagger doc looks weird. For ex: It accept null value, but it's required in swagger.

torshid commented 3 months ago

Are you using version 3.x?

abccbaandy commented 3 months ago

Yes, I also test with 2.x, the same issue.

Btw I use springdoc to generate the swagger doc. https://springdoc.org/

abccbaandy commented 3 months ago

Hi @torshid Seems springdoc team already know this issue, and it's followed the spring way (ask user to add @RequestParam(required = false)). ref: https://github.com/springdoc/springdoc-openapi/issues/252#issuecomment-564777773

Any other way?

torshid commented 3 months ago

Not sure of the source of the problem, but you can try using a String parameter and then parse it later:

@Autowired
private FilterParser filterParser;

@Autowired
private FilterSpecificationConverter filterSpecificationConverter;

@GetMapping
public List<Entity> search(@RequestParam String filter) {
  FilterNode node = filterParser.parse(filter);
  FilterSpecification<Entity> spec = filterSpecificationConverter.convert(node);
  return repository.findAll(spec);
}
abccbaandy commented 3 months ago

Thanks @torshid , it work in 3.x, but it seems filterSpecificationConverter not exist in 2.x ?

Also it looks like a workaround, with many extra code.

Hope we can have a fix about this issue.

torshid commented 3 months ago

There should be similar classes to achieve the same goal in 2.x. It's a workaround yes but I don't see any other way to do it currently since it's a problem with springdoc, using String gives you more flexibility. You can also write your own interceptors.