【问题标题】:Next.js with SwaggerNext.js 与 Swagger
【发布时间】:2021-07-01 11:14:55
【问题描述】:

有没有办法为 NEXT.js API 路由提供一个招摇的文档? 我正在使用 Next.js 进行前端和后端开发,并且我希望为我使用 Next.js 开发的 API 提供一个招摇的文档。

【问题讨论】:

    标签: javascript swagger next.js


    【解决方案1】:

    我制作了一个小型 npm 库,可以从您的 NextJS 项目中自动生成 Swagger 文档。无需用户输入!

    仍然是测试版,但希望它有用。 https://www.npmjs.com/package/nextjs-routes-docs

    快跑

    npx nextjs-routes-docs [dir]
    

    【讨论】:

      【解决方案2】:

      您可以使用以下项目来引导 Next.js 和 Swagger 之间的集成

      yarn add next-swagger-doc swagger-ui-react
      
      import { GetStaticProps, InferGetStaticPropsType } from 'next';
      
      import { createSwaggerSpec } from 'next-swagger-doc';
      import SwaggerUI from 'swagger-ui-react';
      import 'swagger-ui-react/swagger-ui.css';
      
      const ApiDoc = ({ spec }: InferGetStaticPropsType<typeof getStaticProps>) => {
        return <SwaggerUI spec={spec} />;
      };
      
      export const getStaticProps: GetStaticProps = async ctx => {
        const spec: Record<string, any> = createSwaggerSpec({
          title: 'NextJS Swagger',
          version: '0.1.0',
        });
        return { props: { spec } };
      };
      
      export default ApiDoc;
      

      Next.js API 路由端点的实际定义如下所示:

      /**
       * @swagger
       * /api/hello:
       *   get:
       *     description: Returns the hello world
       *     responses:
       *       200:
       *         description: hello world
       */
      const handler = (_req: NextApiRequest, res: NextApiResponse) => {
        res.status(200).json({
          result: 'hello world',
        });
      };
      

      【讨论】:

        【解决方案3】:

        您必须拥有 APIS 的 swagger json 文件或规范,并且可以使用诸如 Swagger UIRedoc 之类的库

        使用 Redoc,您可以执行 /doc/[slug].js 并为您的文档(或 swagger ui)动态获取 .json 或 yaml 文件

        这个网站:https://openapi.tools/,有很多通用的 React 和 OpenAPI 工具供你使用。

        【讨论】:

          猜你喜欢
          • 2022-08-07
          • 2021-07-05
          • 1970-01-01
          • 2017-06-13
          • 2019-12-27
          • 2021-01-23
          • 1970-01-01
          • 1970-01-01
          • 2021-05-03
          相关资源
          最近更新 更多