如何为 Kotlin 数据类中的属性设置 OpenAPI 类型/架构

Fli*_*ter 3 kotlin openapi microprofile quarkus

在使用 Kotlin 的 Microprofile / Quarkus 项目中,有一个数据类,其变量类型为 Instant。

@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    var time: Instant = Instant.EPOCH
)
Run Code Online (Sandbox Code Playgroud)

问题是生成的openapi schema并不能代表Instant的值是如何实际传输的。

架构如下所示,而它只是简单地表示为这样的字符串: 2015-06-02T21:34:33.616Z.

Instant:
  type: object
  properties:
    nanos:
      format: int32
      type: integer
    seconds:
      format: int64
      type: integer
    epochSecond:
      format: int64
      type: integer
    nano:
      format: int32
      type: integer
Run Code Online (Sandbox Code Playgroud)

我已经尝试注释数据类以使用实现字符串和类型字符串,但它没有改变任何东西。

@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    @Schema(implementation = String::class, type = SchemaType.STRING)
    var time: Instant = Instant.EPOCH
)
Run Code Online (Sandbox Code Playgroud)

Mar*_*vin 5

问题是数据类接受了一些特殊处理,并且您的注释放在构造函数参数上

您可以在数据类生成的 Java 代码中看到这一点。相关片段:

@Schema(
   name = "Vehicle",
   description = "POJO that represents a vehicle at a specific time."
)
@Metadata(...)
public final class VehicleDTO {
   @NotNull
   private Instant time;

   @NotNull
   public final Instant getTime() {
      return this.time;
   }

   public final void setTime(@NotNull Instant var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.time = var1;
   }

   public VehicleDTO(@Schema(implementation = String.class,type = SchemaType.STRING) @NotNull Instant time) {
      Intrinsics.checkParameterIsNotNull(time, "time");
      super();
      this.time = time;
   }

   // ...
}
Run Code Online (Sandbox Code Playgroud)

您需要告诉 Kotlin 使用use-site target将其放置在字段

@Schema(name = "Vehicle", description = "POJO that represents a vehicle at a specific time.")
data class VehicleDTO(
    @field:Schema(implementation = String::class, type = SchemaType.STRING)
    var time: Instant = Instant.EPOCH
)
Run Code Online (Sandbox Code Playgroud)

之后的相关代码:

@Schema(
   name = "Vehicle",
   description = "POJO that represents a vehicle at a specific time."
)
@Metadata(...)
public final class VehicleDTO {
   @Schema(
      implementation = String.class,
      type = SchemaType.STRING
   )
   @NotNull
   private Instant time;

   @NotNull
   public final Instant getTime() {
      return this.time;
   }

   public final void setTime(@NotNull Instant var1) {
      Intrinsics.checkParameterIsNotNull(var1, "<set-?>");
      this.time = var1;
   }

   public VehicleDTO(@NotNull Instant time) {
      Intrinsics.checkParameterIsNotNull(time, "time");
      super();
      this.time = time;
   }

   // ...
}
Run Code Online (Sandbox Code Playgroud)