【问题标题】:Swagger Codegen 3 and Spring HATEOASSwagger Codegen 3 和 Spring HATEOAS
【发布时间】:2019-10-08 06:46:07
【问题描述】:

我第一次尝试使用 OAS 3.0、Swagger Codegen、Spring MVC 和 Spring HATEOAS 创建一个 RESTful API。我想使用 OAS 定义生成文档和生成服务器/客户端存根,并使用 HATEOAS 创建超链接相关资源。

我目前拥有扩展 ResourceSupport 的资源,并且可以添加我的链接,以便响应具有我期望的 _embedded 和 _links 字段。我的问题是如何将 HATEOAS Resource 正确映射到 Swagger codegen 生成的模型。我的 OAS 定义与 hal+json 响应匹配,因此 swagger 模型和我的 HATEOAS Response 中的字段相同。

有没有办法轻松映射这些?我也愿意接受我对此的解释不正确,并且这些框架并没有真正融合在一起。

OAS 示例:

responses:
  200:
    description: ...
    content:
      application/hal+json:
        schema:
          $ref: '#/components/schemas/OasPersonResponse'

components:
  schemas:
    OasPersonResponse:
      type: object
          properties:
            firstName:
              type: string
            lastName:
              type: string
            _links:
              type: object
              properties:
                self:
                  type: object
                  properties:                  
                    href:
                    type: string

Resource 示例:

public class PersonResource extends ResourceSupport {
  private final Person person;

  public PersonResource(Person person) {
    this.person = person;
  }

  public String getFirstName() {
    return person.getFirstName();
  }

  public String getLastName() {
    return person.getLastName();
  }
}

控制器示例:

@Controller
public class PersonController implements PersonApi {

  @Override
  public ResponseEntity<OasPersonResponse> getPersonById(Integer personId) {
    Person person = someDb.getPerson(personId);
    PersonResource personResource = new PersonResource(person);

    personResource
      .add(linkTo(methodOn(PersonController.class)
        .getPersonById(personId))
      .withSelfRel();

    Resource<PersonResource> returnResource = 
      new Resource(personResource);

    return new ResponseEntity<>(returnResponse, HttpStatus.OK);
}

我的问题是由 swagger codegen 生成的存根期望返回类型为ResponseEntity&lt;OasPersonResponse&gt;,但引用了Resource&lt;PersonResource&gt;。 OasPersonResponse 和 PersonResource 都表示相同的数据,但 OasPersonResponse 明确定义了 _links 对象,而带有 PersonResource 的响应被序列化为具有 _links 对象。

有没有一种简单的方法可以将 HATEOAS 资源转换为由 swagger codegen 创建的模型?

提前感谢您的帮助和指导。

【问题讨论】:

    标签: java spring-boot openapi spring-hateoas swagger-codegen


    【解决方案1】:

    我目前正在从事一个非常相似的项目! 首先,如果可以的话,我建议使用 spring-hateoas 的 1.0.0.RC1 版本,因为它在 0.25.x 发布分支上具有一些相当重要的生活质量改进。主要相关的是使用EntityModel 包装类现在是推荐的做法,这意味着您可以将关系排除在基本实体规范之外。 (缺点是这降低了 OpenAPI 规范的直接效用;我还没有完全弄清楚如何协调它。)

    其次,就支持 Spring HATEOAS 而言,恐怕在 swagger-codegen 方面似乎没有太多现有的工作;事实上,我一直在使用普通的 Spring“语言”生成器遇到烦人的错误。

    因此,我们可以为 spring-hateoas 编写自己的 swagger-codegen 生成器,或者只是大量自定义一些模板以“足够接近”(使用 EntityModel 包装器而不是扩展 ResourceSupport )。到目前为止,我已经采用了后一种方法,因为这是值得的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-17
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多