【问题标题】:how to have array of paths in swagger?如何大摇大摆地拥有一系列路径?
【发布时间】:2021-09-05 18:18:53
【问题描述】:

我正在学习招摇。我在我的节点应用程序中使用 swagger-ui-express 包来获取文档。我有不止一个文件和很多路径。如何将数组传递给 paths 属性,以便最大程度地减少代码重复?

我的代码:

const paths = [
  {
    "/user/my-account": {
      get: {
        responses: {
          "200": {
            description: "Fetched Account successfully",
          },
          "404": {
            description: "No Account was found",
          },
        },
      },
    },
  },
];

const swaggerConfig = {
  openapi: "3.0.0",
  info: {
    version: "0.0.1",
    title: "Swagger UI",
    description: " Swagger UI",
  },
  servers: [
    {
      url: "http://localhost:4000/",
      description: "Local server",
    },
  ],
  paths: paths.map((path) => {
    return path;
  }),
};

export default swaggerConfig;

我需要完成这项工作。我该怎么办?

【问题讨论】:

  • 为什么不将您的数组处理成一个可以与路径参数一起使用的对象?就像在具有路径键和值作为路径元数据的对象中一样。好像你快到了。可能使用数组减少吧?
  • @AlexanderStaroselsky 它没有显示在浏览器中,我也不确定如何与路径属性匹配。如果您不介意可以分享代码吗?
  • 这是一个来自 swagger express ui 库的官方 json 示例:github.com/scottie1984/swagger-ui-express/blob/master/test/…。请注意,paths 是一个对象而不是数组。首先尝试将数组更改为对象。您可以将数组归约与 object.entries 或 object.keys 一起使用。如果您仍然遇到问题,请展示您尝试的方法,然后可以提供进一步帮助。
  • 但是我只从映射中返回一个对象
  • @AlexanderStaroselsky 我完全不知道该怎么做

标签: javascript swagger swagger-ui


【解决方案1】:

你可以这样试试:

let swaggerPaths = {};
const apis = [
  {
    path: "/user/my-account",
    respondWith: {
      get: {
        responses: {
          "200": {
            description: "Fetched Account successfully",
          },
          "404": {
            description: "No Account was found",
          },
        },
      },
    },
  },
  {
    path: "/user/my-account-2",
    respondWith: {
      get: {
        responses: {
          "200": {
            description: "Fetched Account successfully",
          },
          "404": {
            description: "No Account was found",
          },
        },
      },
    },
  },
];

apis.map((api) => (swaggerPaths[api.path] = api.respondWith));

const swaggerConfig = {
  openapi: "3.0.0",
  info: {
    version: "0.0.1",
    title: "Swagger UI",
    description: "Swagger UI",
  },
  servers: [
    {
      url: "http://localhost:4000/",
      description: "Local server",
    },
  ],
  paths: {...swaggerPaths, /* any other object eg : ...productPaths*/ },
};

export default swaggerConfig;

【讨论】:

  • 哇,顺便说一句,我怎么能有多个对象?喜欢路径:userApi,但我需要做类似路径:{ userApi,productApi},但这不起作用
  • 非常感谢兄弟
猜你喜欢
  • 2020-08-19
  • 2019-05-11
  • 1970-01-01
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多