【发布时间】:2021-07-01 11:14:55
【问题描述】:
有没有办法为 NEXT.js API 路由提供一个招摇的文档? 我正在使用 Next.js 进行前端和后端开发,并且我希望为我使用 Next.js 开发的 API 提供一个招摇的文档。
【问题讨论】:
标签: javascript swagger next.js
有没有办法为 NEXT.js API 路由提供一个招摇的文档? 我正在使用 Next.js 进行前端和后端开发,并且我希望为我使用 Next.js 开发的 API 提供一个招摇的文档。
【问题讨论】:
标签: javascript swagger next.js
我制作了一个小型 npm 库,可以从您的 NextJS 项目中自动生成 Swagger 文档。无需用户输入!
仍然是测试版,但希望它有用。 https://www.npmjs.com/package/nextjs-routes-docs
快跑
npx nextjs-routes-docs [dir]
【讨论】:
您可以使用以下项目来引导 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',
});
};
【讨论】:
您必须拥有 APIS 的 swagger json 文件或规范,并且可以使用诸如 Swagger UI 或 Redoc 之类的库
使用 Redoc,您可以执行 /doc/[slug].js 并为您的文档(或 swagger ui)动态获取 .json 或 yaml 文件
这个网站:https://openapi.tools/,有很多通用的 React 和 OpenAPI 工具供你使用。
【讨论】: