Created
September 25, 2018 18:03
-
-
Save rehevkor5/6374faa255a56174ec9307df5049f9a1 to your computer and use it in GitHub Desktop.
Swagger plugin for dynamic allowed values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mydomain.swagger; | |
import mydomain.repo.AttributeMetadataRepo; | |
import com.fasterxml.jackson.databind.ObjectMapper; | |
import com.google.common.base.Optional; | |
import io.swagger.annotations.ApiParam; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.core.annotation.Order; | |
import org.springframework.stereotype.Component; | |
import springfox.documentation.spi.DocumentationType; | |
import springfox.documentation.spi.service.ParameterBuilderPlugin; | |
import springfox.documentation.spi.service.contexts.ParameterContext; | |
import springfox.documentation.swagger.common.SwaggerPluginSupport; | |
/** | |
* Handles parameters with allowed value list that is dynamically retrieved from database. To activate this plugin, set | |
* the allowableValues property of the @ApiParam annotation to "dynamic[whatever]". | |
*/ | |
@Component | |
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER + 1) | |
public class ParameterDynamicAllowedValuesBuilder implements ParameterBuilderPlugin { | |
private final AttributeMetadataRepo repo; | |
private final ObjectMapper mapper; | |
@Autowired | |
public ParameterDynamicAllowedValuesBuilder(AttributeMetadataRepo repo, ObjectMapper mapper) { | |
this.repo = repo; | |
this.mapper = mapper; | |
} | |
@Override | |
public void apply(ParameterContext context) { | |
@SuppressWarnings("Guava") final Optional<ApiParam> apiParam = | |
context.resolvedMethodParameter().findAnnotation(ApiParam.class); | |
if (apiParam.isPresent()) { | |
final String allowableValuesString = apiParam.get().allowableValues(); | |
if ("dynamic[whatever]".equals(allowableValuesString)) { | |
context.parameterBuilder().allowableValues(new DynamicAllowableValues(repo)); | |
} | |
} | |
} | |
@Override | |
public boolean supports(DocumentationType delimiter) { | |
return SwaggerPluginSupport.pluginDoesApply(delimiter); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I needed to set the
parameterType
inparmeterBuilder
toquery
as well for it to work as intended.