【问题标题】:Spring cloud contracts with generic api具有通用 API 的 Spring Cloud 合约
【发布时间】:2020-06-23 10:05:42
【问题描述】:

如何通过通用 api 使用 Spring Cloud 合约。我在询问有关生产者服务的 REST 合同。所以考虑一个例子。我有一项服务,它允许将用户数据以不同格式存储到数据库中,并充当服务和数据库之间的代理。它具有所有消费者所需的参数,以及依赖于消费者的参数。

class Request<T> {
    Long requestId;
    String documentName;
    T documentContent;
}

它有两个消费者。

消费者1:

{
  "requestId": 1,
  "documentName": "login-events",
  "documentContent": {
    "userId": 2,
    "sessionId": 3
  }
}

消费者2:

{
  "requestId": 1,
  "documentName": "user-details",
  "documentContent": {
    "userId": 2,
    "name": "Levi Strauss",
    "age": 11
  }
}

如您所见,documentContent 取决于消费者。在我想编写这样的合同时,它将在消费者端检查该字段的内容并在生产者端忽略它。像

这样的选项
"documentContent": ["age": $(consumer(11))] //will produce .field(['age']").isEqualTo(11)

"documentContent": ["age": $(consumer(11), producer(optional(anInteger())))] //will require field presence

没用。当然,我可以写"documentContent": [] 甚至忽略合同中的这个字段,但我希望它们像 Rest Api 文档一样工作。有人知道如何解决这个问题吗?

【问题讨论】:

    标签: spring spring-cloud-contract contract


    【解决方案1】:

    忽略可选元素并定义 2 个合同。一个有age 值,一个没有它。具有age 值的那个应该还包含一个priority 字段。你可以在这里阅读优先级https://cloud.spring.io/spring-cloud-static/spring-cloud-contract/2.2.0.RELEASE/reference/html/project-features.html#contract-dsl-http-top-level-elements

    看起来或多或少像这样(YAML 中的合同):

    priority: 5 # lower value of priority == higher priority
    request:
      ...
      body:
         documentContent:
             age: 11
    response:
      ...
    

    然后是不太具体的案例(在 YAML 中)

    priority: 50 # higher value of priority == lower priority
    request:
      ...
      body:
         documentContent:
             # no age
    response:
      ...
    

    【讨论】:

      【解决方案2】:

      我找到了更适合我的情况的解决方案(常规代码):

      def documentContent = [
        "userId": 2,
        "sessionId": 3
      ]
      Contract.make {
        response {
          body(
            [
            ............
            "documentContent" : $(consumer(documentContent), producer(~/.+/)),
            ............
            ]
          )
        }
      }
      

      但请注意,我在生产者合同测试中将 documentContent 值与 String(“documentContent”)存根。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-03
        • 2017-07-23
        • 1970-01-01
        • 1970-01-01
        • 2018-04-03
        • 2021-02-15
        • 2019-02-01
        相关资源
        最近更新 更多