簡體   English   中英

Map 字符串到數組打開 API 和 NestJS

[英]Map strings to Array on Open API and NestJS

我的目標是通過 NestJS 項目生成 swagger 規范,直到現在一切正常。 當我想指定返回數據是一個在運行時將鍵映射到自定義對象數組的 Dict 時,問題就出現了。

我在這里閱讀了文檔https://swagger.io/docs/specification/data-models/dictionaries/和一些相關內容,並了解到我可以為任何 object 創建一個 map 的字符串,但我無法與鍵入的 Arrays 相關聯.

重要的是要注意,我不知道鍵是什么以及每個數組中將包含多少對象,我只知道該值將是特定類型的數組。

這是我的數據示例:

{
  "1":[CustomObjectType, CustomObjectType, CustomObjectType],
  "5":[CustomObjectType, CustomObjectType]
}

所以我認為在 Swagger 上它應該是這樣的:

components:
  schemas:
    CustomMap:
      type: object
      additionalProperties:
        $ref: '#/components/schemas/CustomObjectType'
        isArray: true

    CustomObjectType:
      type: object
      ...

但我無法正確理解。 如果我在 Swagger 中發現我是如何做的,我就能弄清楚如何將它傳遞給 NestJS。

我嘗試使用 class 作為類型,但它沒有 map 屬性:

export class CustomObjectDTO {
  [x: string]: Array<CustomObjectType>;
}

我最后一次嘗試是使用@ApiResponse

@ApiResponse({
    status: 200,
    schema: {
      type: 'object',
      additionalProperties: {
        type: getSchemaPath(CustomObjectType),
      },
    },
  })

這幾乎是我所需要的,但它忽略了值實際上是 CustomObjectType 的數組

解決方案@lia的問題帖子中移出。

通過使用值類型作為數組並將項目的類型定義為我的 CustomObjectType 找到了解決方案。 例子:

 components: schemas: CustomMap: type: object additionalProperties: type: array items: $ref: '#/components/schemas/CustomObjectType' CustomObjectType: type: object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM