Node.js自動生成API文檔的實現(xiàn)
如何在Node.js項目中使用 Swagger 來自動生成 API接口文檔,使用生成方式有很多種。本文基于swagger-jsdoc+swagger-ui-express快速實現(xiàn)
1、直接使用swagger-ui-express
// 方便來瀏覽和測試api npm i swagger-ui-express
import { Express } from 'express';
import swaggerUi from 'swagger-ui-express';
const options = {
openapi: "3.0.3",
info: {
title: '文檔相關(guān)接口',
version: '1.0.0',
description: 'API documentation using Swagger',
},
tags: [{
name: "develop",
description: "開發(fā)者站點(diǎn)管理接口",
}],
paths: {
"/develop": {
"get": {
"tags": ["develop"],
"description": "獲取文檔列表!",
"responses": {
"200": {
"description":"返回字符串?dāng)?shù)組"
}
}
}
}
}
}
const swaggerInstall = (app: Express) => {
app.use(
'/apidoc',
swaggerUi.serve,
swaggerUi.setup(options)
);
};
export { swaggerInstall };

直接使用配置去生成接口文檔,更改接口的時候需要同時去更改配置,會相對麻煩點(diǎn)。這時候就可以使用swagger-jsdoc,通過在接口上面注釋信息后,就可以自動更新對應(yīng)的api接口文檔,其本質(zhì)是通過讀取該接口對應(yīng)的注釋,然后再轉(zhuǎn)成對應(yīng)的配置。
2、配合swagger-jsdoc
JSDoc 注釋是一種特殊的注釋語法,用于為 JavaScript 代碼添加文檔化和類型提示信息。它是基于 JSDoc 規(guī)范的一部分,旨在提供一種標(biāo)準(zhǔn)的方式來描述代碼的結(jié)構(gòu)、功能和類型信息
作用:接口文檔注釋有更新,對應(yīng)的api文檔會同步更新。確保接口變更,配置會同時去更改
npm i swagger-jsdoc
import { Express } from 'express';
import path from 'path';
import swaggerDoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
const swaggerOptions = {
swaggerDefinition: {
info: {
title: '文檔相關(guān)接口',
version: '1.0.0',
description: 'API documentation using Swagger',
},
},
apis: [path.join(__dirname, './routes/*.ts')], // 指定包含 API 路由的文件或文件夾路徑
};
const swaggerInstall = (app: Express) => {
app.use(
'/apidoc',
swaggerUi.serve,
swaggerUi.setup(swaggerDoc(swaggerOptions))
);
};
export { swaggerInstall };
//在對應(yīng)的接口,注釋對應(yīng)的文檔
import express from 'express';
import {
developGetFile,
developGetFileList,
} from '../controllers/developControllers';
const router = express.Router();
/**
* @openapi
* /develop:
* get:
* tags: [develop]
* description: 獲取文檔列表!
* responses:
* 200:
* description: 返回字符串?dāng)?shù)組.
*/
router.get('/', developGetFileList);
到此這篇關(guān)于Node.js自動生成API文檔的文章就介紹到這了,更多相關(guān)Node.js自動生成API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何在Nestjs和Vue3中使用socket.io示例詳解
這篇文章主要為大家介紹了如何在Nestjs和Vue3中使用socket.io示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
NodeJS學(xué)習(xí)筆記之Connect中間件應(yīng)用實例
前面我們介紹了幾篇內(nèi)容的connect中間件的基礎(chǔ)知識,今天我們來實例應(yīng)用一下,做個記事本的小應(yīng)用,希望大家能夠喜歡。2015-01-01
NodeJS和BootStrap分頁效果的實現(xiàn)代碼
這篇文章主要介紹了NodeJS和BootStrap分頁效果的實現(xiàn)代碼的相關(guān)資料,非常不錯具有參考借鑒價值,需要的朋友可以參考下2016-11-11

