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

kxkpmulp  于 2024-01-08  发布在  其他
关注(0)|答案(1)|浏览(248)

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

  1. "responses": {
  2. "200": {
  3. "content": {
  4. "application/json": {
  5. "schema": {
  6. "properties": {
  7. "data": {
  8. "type": "array",
  9. "items": {
  10. "$ref": "#/components/schemas/AdminApi-AdminResource"
  11. }
  12. },
  13. "meta": {
  14. $ref: "#/components/schemas/PaginationMeta"
  15. }
  16. },
  17. "type": "object"
  18. }
  19. }
  20. }
  21. }
  22. }

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

  1. {
  2. "title": "Admin api admin resource",
  3. "description": "Admin api admin resource",
  4. "properties": {
  5. "id": {
  6. "type": "integer",
  7. "example": 1
  8. },
  9. "email": {
  10. "type": "string",
  11. "example": "[email protected]"
  12. },
  13. "created_at": {
  14. "type": "string",
  15. "example": "2022-10-17T13:55:59.000000Z"
  16. },
  17. "updated_at": {
  18. "type": "string",
  19. "example": "2022-10-17T13:55:59.000000Z"
  20. }
  21. },
  22. "type": "object"
  23. }


#/components/schemas/PaginationMeta

  1. {
  2. "properties": {
  3. "current_page": {
  4. "type": "number",
  5. "example": 1
  6. },
  7. "from": {
  8. "type": "number",
  9. "example": 1
  10. },
  11. "last_page": {
  12. "type": "number",
  13. "example": 1
  14. },
  15. "per_page": {
  16. "type": "number",
  17. "example": 100
  18. },
  19. "to": {
  20. "type": "number",
  21. "example": 1
  22. },
  23. "total": {
  24. "type": "number",
  25. "example": 1
  26. }
  27. },
  28. "type": "object"
  29. }


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

  1. {
  2. "data": {
  3. "items": [
  4. {
  5. "id": 1,
  6. "email": "[email protected]",
  7. "created_at": "2022-10-17T13:55:59.000000Z",
  8. "updated_at": "2022-10-17T13:55:59.000000Z"
  9. }
  10. ]
  11. },
  12. "meta": {
  13. "current_page": 1,
  14. "from": 1,
  15. "last_page": 1,
  16. "per_page": 100,
  17. "to": 1,
  18. "total": 1
  19. }
  20. }


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

fwzugrvs

fwzugrvs1#

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

  • @apidevtools/swagger-parser-解析OpenAPI规范并将$ref替换为规范组件中的相应值。
  • openapi-sampler-基于OpenAPI payload/response schema生成示例,并以代码高亮显示。
  1. import SwaggerParser from '@apidevtools/swagger-parser';
  2. // To replace $ref with corresponding value from spec
  3. const dereferencedData = await SwaggerParser.dereference(data);

个字符

相关问题