OpenAPI 生成器可使用 Spring 进行分页

Blo*_*lex 13 java spring code-generation openapi openapi-generator

我希望 OpenAPI 生成器(https://github.com/OpenAPITools/openapi-generator)能够根据 Spring Boot Data 中的实现在 API 中生成 Pageable 参数。我一直在尝试寻找一种合适的开箱即用的解决方案,但找不到。

理想情况下,此 Pageable 参数应仅按以下方式添加到 GET 方法:

default ResponseEntity<User> getUser(@ApiParam(value = "value",required=true) @PathVariable("id") Long id, **Pageable pageable**)
Run Code Online (Sandbox Code Playgroud)

因此,在我的控制器中实现此接口后,我需要重写它并具有上述的 Pageable 参数。我不想有单独的大小或页面参数,这里只有这个可分页。

感谢您的任何提示和帮助!

小智 10

不幸的是,这不是最终的解决方案,但它已经完成了一半。也许无论如何它都有帮助。

通过将可分页参数(大小、页面等)定义为对象查询参数,可以告诉生成器使用 Spring 对象,而不是Pageable从 api 生成类。这是通过导入映射完成的。

在 gradle 中:

openApiGenerate {
    ....
    importMappings = [
        'Pageable': 'org.springframework.data.domain.Pageable'
    ]
}
Run Code Online (Sandbox Code Playgroud)

它告诉生成器使用 Spring 类而不是 api 中定义的类:

openapi: 3.0.2
info:
  title: Spring Page/Pageable API
  version: 1.0.0

paths:
  /page:
    get:
      parameters:
        - in: query 
          name: pageable
          required: false
          schema:
            $ref: '#/components/schemas/Pageable'
      responses:
        ...

components:
  schemas:
    Pageable: 
      description: minimal Pageable query parameters
      type: object
      properties:
        page:
          type: integer
        size:
          type: integer
Run Code Online (Sandbox Code Playgroud)

映射的问题在于生成器仍然添加@RequestParam()注释并再次破坏它。只有在没有注释的情况下它才有效。

如果你有点冒险精神,你可以尝试openapi-processor-spring(我是作者)。它确实处理了上面的例子。但它可能还有其他您不喜欢的限制。