swagger 如何将OpenAPI响应示例内容转换为简单的JSON,以便代码高亮显示?

kxkpmulp  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(169)

我想在highlight.js中显示OpenAPI v3.0.0规范的paths.{url}.{method}.responses部分中的响应示例内容。我目前正在从远程JSON OpenAPI规范中获取此类对象:

"responses": {
    "200": {
        "content": {
            "application/json": {
                "schema": {
                    "properties": {
                        "data": {
                            "type": "array",
                            "items": {
                                "$ref": "#/components/schemas/AdminApi-AdminResource"
                            }
                        },
                        "meta": {
                            $ref: "#/components/schemas/PaginationMeta"
                        }
                    },
                    "type": "object"
                }
            }
        }
    }
}

字符串
#/components/schemas/AdminApi-AdminResource

{
    "title": "Admin api admin resource",
    "description": "Admin api admin resource",
    "properties": {
        "id": {
            "type": "integer",
            "example": 1
        },
        "email": {
            "type": "string",
            "example": "[email protected]"
        },
        "created_at": {
            "type": "string",
            "example": "2022-10-17T13:55:59.000000Z"
        },
        "updated_at": {
            "type": "string",
            "example": "2022-10-17T13:55:59.000000Z"
        }
    },
    "type": "object"
}


#/components/schemas/PaginationMeta

{
    "properties": {
        "current_page": {
            "type": "number",
            "example": 1
        },
        "from": {
            "type": "number",
            "example": 1
        },
        "last_page": {
            "type": "number",
            "example": 1
        },
        "per_page": {
            "type": "number",
            "example": 100
        },
        "to": {
            "type": "number",
            "example": 1
        },
        "total": {
            "type": "number",
            "example": 1
        }
    },
    "type": "object"
}


我需要将这些响应对象从OpenAPI解析/转换为简单的JS/JSON对象:

{
    "data": {
        "items": [
            {
                "id": 1,
                "email": "[email protected]",
                "created_at": "2022-10-17T13:55:59.000000Z",
                "updated_at": "2022-10-17T13:55:59.000000Z"
            }
        ]
    },
    "meta": {
        "current_page": 1,
        "from": 1,
        "last_page": 1,
        "per_page": 100,
        "to": 1,
        "total": 1
    }
}


并以代码高亮显示这些简单对象,例如highlight.js
我不知道如何解决这个问题,或者我应该从什么方向开始寻找这个问题。

fwzugrvs

fwzugrvs1#

经过几个小时的搜索,我发现了两个有用的软件包,可以帮助实现上述问题中描述的目标。

  • @apidevtools/swagger-parser-解析OpenAPI规范并将$ref替换为规范组件中的相应值。
  • openapi-sampler-基于OpenAPI payload/response schema生成示例,并以代码高亮显示。
import SwaggerParser from '@apidevtools/swagger-parser';

// To replace $ref with corresponding value from spec
const dereferencedData = await SwaggerParser.dereference(data);

个字符

相关问题