如何大摇大摆地拥有一系列路径?

how to have array of paths in swagger?

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

我的代码:

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;

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

你可以这样试试:

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;