SpringCloud + React19 集成Scalar的API文档

你好呀,我的老朋友!我是老寇,跟我一起学习集成Scalr API文档

众所周知,Knife4j是一个集Swagger2 和 OpenAPI3 为一体的增强解决方案,但是社区不太活跃,再加上SpringBoot4 发版,迫切需要一个集成 OpenAPI 3.0 和 OpenAPI 3.1 规范的增强解决方案,所以才集成Scalar

React集成Scalar

React集成Scalar文档地址

安装依赖
shell 复制代码
pnpm install @scalar/api-reference-react
配置详情
配置项 类型 是否必填 说明 示例
sources Array 是 OpenAPI 文档源列表,一个配置可以配置多个 API 文档。 [{ title: "认证授权", url: "/api/v3/api-docs" }]
sources.title String 是 API 文档名称,在 Scalar 左侧导航中显示。 "认证授权"
sources.url String 是 OpenAPI(Swagger)JSON 文档地址。 "/api-proxy/auth/api/v3/api-docs"
sources.default Boolean 否 是否默认选中该文档。 true
proxyUrl String 否 Scalar 的代理地址,用于 Try It、鉴权等请求代理。 "/api-proxy/auth/scalar"
expandAllResponses Boolean 否 是否默认展开所有 Response。 true
hideClientButton Boolean 否 是否隐藏 Generate Client(生成客户端)按钮。 true
orderRequiredPropertiesFirst Boolean 否 Model 属性中,是否将必填字段排在前面。 true
expandAllModelSections Boolean 否 是否默认展开所有 Model 定义。 false
具体代码

apiDoc.tsx

javascript 复制代码
import {ApiReferenceReact} from '@scalar/api-reference-react'
import '@scalar/api-reference-react/style.css'
import { useIntl } from '@@/exports';

export default () => {
    const intl = useIntl();
    const t = (id: string, values?: Record<string, any>) =>
       intl.formatMessage({ id }, values);
    return (
       <ApiReferenceReact
          configuration={
          [
             {
                sources: [
                   {
                      title: '认证授权',
                      url: "/api-proxy/auth/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/auth/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             },
             {
                sources: [
                   {
                      title: '后台管理',
                      url: "/api-proxy/admin/api/v3/api-docs",
                      default: true,
                   }
                ],
                proxyUrl: "/api-proxy/admin/scalar",
                expandAllResponses: true,
                hideClientButton: true,
                orderRequiredPropertiesFirst: true,
                expandAllModelSections: false,
             }
          ]
       }
       />
    );
};

Spring Cloud Gateway集成Scalar

由于代理地址为 /**/scalar 因此,需要在网关层将 /**/scalar 覆盖为 scalar_url

依赖
复制代码
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-gateway-server-webflux</artifactId>
</dependency>
具体代码

ScalarGatewayFilterFactory

java 复制代码
@Slf4j
@Component
public class ScalarGatewayFilterFactory extends AbstractGatewayFilterFactory<ScalarGatewayFilterFactory.@NonNull Config>
       implements Ordered {

    public ScalarGatewayFilterFactory() {
       super(Config.class);
    }

    @Override
    public int getOrder() {
       return Ordered.LOWEST_PRECEDENCE - 2000;
    }

    @NonNull
    @Override
    public GatewayFilter apply(Config config) {
       return (exchange, chain) -> {
          ServerHttpRequest request = exchange.getRequest();
          // 获取uri
          String requestURL = ReactiveRequestUtils.getRequestURL(request);
          // scalar重写地址
          if (ReactiveRequestUtils.pathMatcher("/**/scalar", requestURL)) {
             String scalarUrl = ReactiveRequestUtils.getParamValue(request, "scalar_url");
             URI uri = URI.create(scalarUrl);
             return chain
                .filter(exchange.mutate().request(request.mutate().uri(uri).path(uri.getPath()).build()).build());
          }
          return chain.filter(exchange);
       };
    }

    public static class Config {

    }

}

application.yml

yaml 复制代码
spring:
  cloud:
    gateway:
      server:
        webflux:
          enabled: true
          routes:
            - id: laokou-auth-scalar
              uri: lb://laokou-auth
              predicates:
                - Path=/api-gateway/auth/scalar
              filters:
                - name: Scalar
            - id: laokou-admin-scalar
              uri: lb://laokou-admin
              predicates:
                - Path=/api-gateway/admin/scalar
              filters:
                - name: Scalar

SpringBoot集成Scalar(以laokou-auth为例)

安装依赖
xml 复制代码
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-scalar</artifactId>
</dependency>
具体代码

OpenApiDocConfig

java 复制代码
@Configuration
public class OpenApiDocConfig {

    @Bean
    OpenAPI openApi() {
       return new OpenAPI()
          .info(new Info().title("API文档")
             .description("API文档")
             .version("1.0.0")
             .contact(new Contact().name("laokou").url("https://github.com/KouShenhai").email("2413176044@qq.com"))
             .license(new License().name("Apache 2.0").url("https://www.apache.org/licenses/LICENSE-2.0.html")))
          .externalDocs(new ExternalDocumentation().description("老寇IoT云平台").url("https://github.com/KouShenhai"))
          .addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
          .components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,
                new SecurityScheme().name(HttpHeaders.AUTHORIZATION)
                   .type(SecurityScheme.Type.OAUTH2)
                   .in(SecurityScheme.In.HEADER)
                   .scheme("Bearer")
                   .bearerFormat("JWT")));

    }

}

application.yml

yaml 复制代码
scalar:
  enabled: true
springdoc:
  swagger-ui:
    enabled: false
  api-docs:
    enabled: true
    path: /v3/api-docs
    version: openapi_3_1

我是老寇,我们下次再见啦!

相关推荐
nice_lcj52021 分钟前
Bean 的作用域:单例、原型及特殊作用域
java·spring·面试·原型·单例·bean作用域
nice_lcj5202 小时前
Spring AOP 面向切面编程:切面解决什么问题
java·spring·面试·aop·切面·面向切面编程
大数据技术派2 小时前
有了AI,你多久没有亲自写代码了?
后端
考虑考虑3 小时前
JDK27的LazyConstant
java·后端·java ee
知识搬运临时工3 小时前
加一层连接池,TPS 从 26438 掉到 12923
java·后端
周末程序猿4 小时前
技术总结|OpenSpec 实战:如何先写规格,再让 AI 写代码
后端·ai编程
计算机–阿拉升学长5 小时前
基于SpringBoot的番茄种植水肥一体化管理系统 — 系统设计与实现
java·spring boot·后端·mysql·vue·javaweb
bai2735 小时前
日志里的 [Object] 不是空对象:console.log 默认只展开两层,console.dir 也一样
javascript·后端
一条Go5 小时前
26 篇之后:Alioth 的 26 个设计决定
后端·github
狗头大军之江苏分军5 小时前
《潮水漫过十七岁》 补一下,运动会
前端·javascript·后端