springdoc / springdoc.github.io

Library for OpenAPI 3 with spring-boot
https://springdoc.org
Apache License 2.0
9 stars 40 forks source link

Customizing swagger static resources #34

Closed shaburov closed 2 years ago

shaburov commented 2 years ago

See issue.

OpenAPI Configuration

@Configuration
public class OpenApiConfig {
  @Bean
  public SwaggerIndexTransformer swaggerIndexTransformer(SwaggerUiConfigProperties sUiConfig,
                                                         SwaggerUiOAuthProperties sUiOAuthProperties,
                                                         SwaggerUiConfigParameters sUiConfigParameters,
                                                         SwaggerWelcomeCommon sWelcomeCommon) {
      return new SwaggerCodeBlockTransformer(sUiConfig, sUiOAuthProperties, sUiConfigParameters, sWelcomeCommon);
  }
}

Transformer

public class SwaggerCodeBlockTransformer extends SwaggerIndexPageTransformer {

    private static final String OLD = ".renderedMarkdown code{" +
                                      "background:rgba(0,0,0,.05);" +
                                      "border-radius:4px;" +
                                      "color:#9012fe;" +
                                      "font-family:monospace;" +
                                      "font-size:14px;font-weight:600;" +
                                      "padding:5px 7px}";
    private static final String NEW = ".renderedMarkdown code{" +
                                      "color:#9012fe;" +
                                      "font-family:monospace;" +
                                      "font-size:14px;font-weight:600}";

    public SwaggerCodeBlockTransformer(SwaggerUiConfigProperties swaggerUiConfig,
                                       SwaggerUiOAuthProperties swaggerUiOAuthProperties,
                                       SwaggerUiConfigParameters swaggerUiConfigParameters,
                                       SwaggerWelcomeCommon swaggerWelcomeCommon) {
        super(swaggerUiConfig, swaggerUiOAuthProperties, swaggerUiConfigParameters, swaggerWelcomeCommon);
    }

    @Override
    public Resource transform(HttpServletRequest request,
                              Resource resource,
                              ResourceTransformerChain transformerChain) throws IOException {
        if (resource.toString().contains("swagger-ui.css")) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
                final String css = reader.lines().collect(Collectors.joining());
                final byte[] transformedContent = css.replace(OLD, NEW).getBytes();
                return  new TransformedResource(resource, transformedContent);
            }
        }
        return super.transform(request, resource, transformerChain);
    }

}
shaburov commented 2 years ago

@bnasslahsen review please