Swagger OpenApi dynamic query param name using annotation for Spring custom resolver

Viewed 925

I'm trying to figure out how to indicate to SpringDoc OpenApi that a custom object is being generated using HandlerMethodArgumentResolver which intercepts some incoming request parameters and creates an object out of it. The concept is actually just the same as Spring does with @Pageable.

Here's some part of my custom object:

class FlightRequestHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
FlightRequestHandlerMethodArgumentResolver() {
}

@Override
boolean supportsParameter(final MethodParameter parameter) {
    return FlightRequest.class.equals(parameter.getParameterType());
}

@Override
Object resolveArgument(
        final MethodParameter parameter,
        final ModelAndViewContainer mavContainer,
        final NativeWebRequest webRequest, final WebDataBinderFactory binderFactory) throws Exception {
    final Map<String, String[]> parameterMap = webRequest.getParameterMap()
    // query param names are configurable
    // implementation about finding query param names is ommited
    return new FlightRequest(parameterMap)
}

FlightRequest class:

public class FlightRequest {

@Parameter(name = "startDate")
private final LocalDate startDate;

@Parameter(name = "endDate")
private final LocalDate endDate;

FlightRequest (LocalDate startDate, LocalDate endDate) {
    this.submissionStartDate = submissionStartDate;
    this.submissionEndDate = submissionEndDate;
}

Controller that uses FlightRequest with default query param names:

@RequestMapping(value = "/flights", method = RequestMethod.GET)
Flights flights(FlightRequest flightRequest, HttpServletResponse response) {
    return flightSearchService.retrieveFlights(flightRequest);
}

Controller that uses FlightRequest with custom query param names:

@RequestMapping(value = "/current-flights", method = RequestMethod.GET)
Flights flights(@FlightRequestParams(fromDateParamName="current-flights-from", toDateParamName="current-flights-till) FlightRequest flightRequest, HttpServletResponse response) {
    return flightSearchService.retrieveFlights(flightRequest);
}

Like you see in the example above, each endpoint can override default query param names.
How can I indicate this to Spring Doc?

1 Answers

It seems you are not using here a spring annotation, but your own: @FlightRequestParams.

If, you really want the default values to be dynamically added, then you can write your own for your annotation DelegatingMethodParameterCustomizer, for your annotation, as it's done for @PageableDefault. Then declare it as a spring Bean, as follow.

Or the simplest way, is to declare the parameter value using @Parameter annotation. You can see an example of PageableAsQueryParam.

Related