【Node.js】Koa2 整合接口文档

部分学习来源:https://blog.csdn.net/qq_38734862/article/details/107715579

依赖

sh 复制代码
// koa2-swagger-ui UI视图组件  swagger-jsdoc 识别写的 /***/ 转 json
npm install koa2-swagger-ui swagger-jsdoc --save

配置

config\swaggerConfig.js

js 复制代码
const Router = require('@koa/router'); // 引入 Router 类
const path = require('node:path');
const swaggerJSDoc = require('swagger-jsdoc');

const swaggerDefinition = {
    info: {
        description:
            'This is a sample server Koa2 server.  You can find out more about     Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).      For this sample, you can use the api key `special-key` to test the authorization     filters.',
        version: '1.0.0',
        title: 'Koa2_server Swagger',
    },
    host: 'localhost:4000',
    basePath: '/', // Base path (optional), host/basePath
    schemes: ['http'],
};

const options = {
    swaggerDefinition,
    // 写有注解的router的存放地址(当你新增swagger时文档里没显示出来的话那么就是这边地址没有加进去)
    apis: ['./routes/*.js'] // 注意这里的路径!!!
};

const swaggerSpec = swaggerJSDoc(options);

// 创建一个新的 Router 实例
const router = new Router();

// 通过路由获取生成的注解文件
router.get('/swagger.json', async ctx => {
    ctx.set('Content-Type', 'application/json');
    ctx.body = swaggerSpec;
});

module.exports = router;

入口文件 app.js 注册:

js 复制代码
const Koa = require('koa');
const app = new Koa();
const {koaSwagger} = require("koa2-swagger-ui");

const attractionRoute = require('./routes/attractionsRoute'); // 添加: 引入景点路由
const swaggerConfig = require('./config/swaggerConfig');

// 使用 Swagger 路由
app.use(swaggerConfig.routes()).use(swaggerConfig.allowedMethods());

// 使用景点路由
app.use(attractionRoute.routes()).use(attractionRoute.allowedMethods());
// 使用 Swagger UI
app.use(
    koaSwagger({
        routePrefix: '/swagger', // host at /swagger instead of default /docs
        swaggerOptions: {
            url: '/swagger.json' // example path to json
        }
    })
);


app.listen(4000, () => {
    console.log('Server is running on port 4000');
});

配置完后打开 http://localhost:4000/swagger 可以得到文档可视化界面,http://localhost:4000/swagger.json 可以看到 swagger 文档配置。

routes 的 swagger 文档注释规范可以参考OpenAPI规范,比如 OpenAPI规范示例。

我的 attrtionsRoute.js 示例:

js 复制代码
const Router = require('@koa/router'); // 添加: 引入路由模块
const router = new Router({ prefix: '/api/scenic' }); // 修改: 创建路由实例,并设置前缀

const attractionsController = require('../controllers/attractionsController');

// 获取景点列表
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/list:
 *   get:
 *     summary: 获取景点列表
 *     responses:
 *       200:
 *         description: 景点列表
 */
router.get('/list', attractionsController.getAttractionsList);

// 获取景点详情
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/{id}:
 *   get:
 *     summary: 获取景点详情
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 景点ID
 *     responses:
 *       200:
 *         description: 景点详情
 */
router.get('/:id', attractionsController.getAttractionById);

// 添加新景点
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/add:
 *   post:
 *     summary: 添加新景点
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               description:
 *                 type: string
 *     responses:
 *       201:
 *         description: 景点添加成功
 */
router.post('/add', attractionsController.addAttraction);

// 更新景点信息
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/update/{id}:
 *   put:
 *     summary: 更新景点信息
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 景点ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *               description:
 *                 type: string
 *     responses:
 *       200:
 *         description: 景点更新成功
 */
router.put('/update/:id', attractionsController.updateAttraction);

// 删除景点
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/delete/{id}:
 *   delete:
 *     summary: 删除景点
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 景点ID
 *     responses:
 *       200:
 *         description: 景点删除成功
 */
router.delete('/delete/:id', attractionsController.deleteAttraction);

// 添加评论
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/comment/{id}:
 *   post:
 *     summary: 添加评论
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 景点ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               comment:
 *                 type: string
 *     responses:
 *       201:
 *         description: 评论添加成功
 */
router.post('/comment/:id', attractionsController.addComment);

// 获取景点评论
// 生成swagger注释
/**
 * @swagger
 * /api/scenic/comments/{id}:
 *   get:
 *     summary: 获取景点评论
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: 景点ID
 *     responses:
 *       200:
 *         description: 景点评论列表
 */
router.get('/comments/:id', attractionsController.getComments);

module.exports = router; // 导出路由实例
相关推荐
wno7041 天前
node.js中使用jquery
前端·node.js·jquery
damoluomu2 天前
Node 的 Headless 出厂没有前台,Java 的 Headless 是从门户里长出来的
java·开发语言·node.js
Dumbness2 天前
一个手机号验证码登录接口的五个坑:无限发码、无限试码,传个数字就让 Express 进程退出
node.js·express
怒放的生命19912 天前
本地用 pnpm 省磁盘,团队继续用 npm:极简实践
前端·npm·node.js
Hone3 天前
我把「自动发文章到掘金」做成了一个 Agent 技能:juejin-skills
node.js·ai编程·前端工程化
Dumbness3 天前
二十行手写的 SKILL.md 头部解析,遇到 YAML 的折叠写法、单引号和嵌套键就读错:和 js-yaml 逐条对照
node.js·ai编程
只睡四小时4 天前
MCP 弃用 SSE?Node 分帧漏 81.7% 事件
node.js·webassembly·实时通信·mcp·streamable http
hey you~4 天前
个体户门店办理400电话,如何对接订单系统实现来电弹窗
node.js·webhook·400电话·门店数字化·来电弹窗·订单系统对接
YIAN5 天前
RAG 学到最后,我真正学会的不是“检索”,而是让系统知道自己缺什么
langchain·node.js·llm