使用 apiDoc 为你的Node.js API 生成文档
翻譯: 瘋狂的技術(shù)宅
原文:jonathas.com/documenting…
未經(jīng)許可,禁止轉(zhuǎn)載!
當(dāng)你為其他開(kāi)發(fā)人員(前端,桌面,移動(dòng)等)開(kāi)發(fā) API 時(shí),需要生成一份風(fēng)格良好的文檔,以便他們知道可以使用的內(nèi)容和方式,這非常重要。
為此,在Node.js項(xiàng)目中,我一直在使用apiDoc,因?yàn)樗軌驈脑创a中的注釋生成HTML文檔。
對(duì)于本文,我將使用我開(kāi)發(fā)的 TODO List API 作為示例。你可以從這里克隆或下載它。
路由和注釋
在我關(guān)于使用 mocha 進(jìn)行測(cè)試并使用 istanbul 進(jìn)行代碼覆蓋測(cè)試的文章中,我在 TODO List API 中顯示了 Task 端點(diǎn)的示例:
import Task from "../controllers/tasks";export = (app) => {const endpoint = process.env.API_BASE + "tasks";app.post(endpoint, Task.create);app.delete(endpoint + "/:id", Task.delete);app.get(endpoint + "/:id", Task.getOne);app.get(endpoint, Task.getAll);app.put(endpoint + "/:id", Task.update); }; 復(fù)制代碼這代表了與系統(tǒng)中任務(wù)相關(guān)的所有端點(diǎn)。我們?cè)鯓硬拍苁褂盟鼈兡?#xff1f;使用 API ??的開(kāi)發(fā)人員應(yīng)該向每個(gè)端點(diǎn)發(fā)送什么數(shù)據(jù)呢?
到現(xiàn)在為止,他們除了去查看代碼之外沒(méi)有其他方法可以搞清楚,但是這些代碼不應(yīng)該被用作這個(gè)目的。
有了 apiDoc,我們可以用注釋來(lái)生成文檔。我的方法是在 routes 目錄下的文件中配置的每個(gè)端點(diǎn)的前面編寫它們。當(dāng)我提到如何配置和組織我的 Node.js 項(xiàng)目時(shí),如果你不確定我在說(shuō)什么請(qǐng) 點(diǎn)擊這里。
使用注釋,我們的任務(wù)端點(diǎn)(內(nèi)部routes/tasks.ts)將如下所示:
import Task from "../controllers/tasks";export = (app) => {const endpoint = process.env.API_BASE + "tasks";/*** @api {post} /api/v1/tasks Create a task* @apiVersion 1.0.0* @apiName Create* @apiGroup Task* @apiPermission authenticated user** @apiParam (Request body) {String} name The task name** @apiExample {js} Example usage:* const data = {* "name": "Do the dishes"* }** $http.defaults.headers.common["Authorization"] = token;* $http.post(url, data)* .success((res, status) => doSomethingHere())* .error((err, status) => doSomethingHere());** @apiSuccess (Success 201) {String} message Task saved successfully!* @apiSuccess (Success 201) {String} id The campaign id** @apiSuccessExample {json} Success response:* HTTPS 201 OK* {* "message": "Task saved successfully!",* "id": "57e903941ca43a5f0805ba5a"* }** @apiUse UnauthorizedError*/app.post(endpoint, Task.create);/*** @api {delete} /api/v1/tasks/:id Delete a task* @apiVersion 1.0.0* @apiName Delete* @apiGroup Task* @apiPermission authenticated user** @apiParam {String} id The task id** @apiExample {js} Example usage:* $http.defaults.headers.common["Authorization"] = token;* $http.delete(url)* .success((res, status) => doSomethingHere())* .error((err, status) => doSomethingHere());** @apiSuccess {String} message Task deleted successfully!** @apiSuccessExample {json} Success response:* HTTPS 200 OK* {* "message": "Task deleted successfully!"* }** @apiUse UnauthorizedError*/app.delete(endpoint + "/:id", Task.delete);/*** @api {get} /api/v1/tasks/:id Retrieve a task* @apiVersion 1.0.0* @apiName GetOne* @apiGroup Task* @apiPermission authenticated user** @apiParam {String} id The task id** @apiExample {js} Example usage:* $http.defaults.headers.common["Authorization"] = token;* $http.get(url)* .success((res, status) => doSomethingHere())* .error((err, status) => doSomethingHere());** @apiSuccess {String} _id The task id* @apiSuccess {String} name The task name** @apiSuccessExample {json} Success response:* HTTPS 200 OK* {* "_id": "57e8e94ea06a0c473bac50cc",* "name": "Do the disehs",* "__v": 0* }** @apiUse UnauthorizedError*/app.get(endpoint + "/:id", Task.getOne);/*** @api {get} /api/v1/tasks Retrieve all tasks* @apiVersion 1.0.0* @apiName GetAll* @apiGroup Task* @apiPermission authenticated user** @apiExample {js} Example usage:* $http.defaults.headers.common["Authorization"] = token;* $http.get(url)* .success((res, status) => doSomethingHere())* .error((err, status) => doSomethingHere());** @apiSuccess {String} _id The task id* @apiSuccess {String} name The task name** @apiSuccessExample {json} Success response:* HTTPS 200 OK* [{* "_id": "57e8e94ea06a0c473bac50cc",* "name": "Do the disehs"* },* {* "_id": "57e903941ca43a5f0805ba5a",* "name": "Take out the trash"* }]** @apiUse UnauthorizedError*/app.get(endpoint, Task.getAll);/*** @api {put} /api/v1/tasks/:id Update a task* @apiVersion 1.0.0* @apiName Update* @apiGroup Task* @apiPermission authenticated user** @apiParam {String} id The task id** @apiParam (Request body) {String} name The task name** @apiExample {js} Example usage:* const data = {* "name": "Run in the park"* }** $http.defaults.headers.common["Authorization"] = token;* $http.put(url, data)* .success((res, status) => doSomethingHere())* .error((err, status) => doSomethingHere());** @apiSuccess {String} message Task updated successfully!** @apiSuccessExample {json} Success response:* HTTPS 200 OK* {* "message": "Task updated successfully!"* }** @apiUse UnauthorizedError*/app.put(endpoint + "/:id", Task.update);}; 復(fù)制代碼如你所見(jiàn),我們有 HTTP 方法的類型(post,put,get,delete)、端點(diǎn)地址、api 版本、它需要的權(quán)限類型、它需要的參數(shù),還有如果用戶是未經(jīng)授權(quán)的應(yīng)該返回怎樣的響應(yīng)和錯(cuò)誤。
在官方網(wǎng)站中,你可以查看注釋文檔和可用參數(shù)。
那么這個(gè) UnauthorizedError 來(lái)自哪里呢?
apiDoc 設(shè)置
有一些設(shè)置可以用 apiDoc 完成,這個(gè) UnauthorizedError 就是我經(jīng)常要用到的。
在 routes 目錄中創(chuàng)建一個(gè)名為 __apidoc.js 的文件,其中包含以下內(nèi)容:
// ----------------------------------------------------------- // General apiDoc documentation blocks and old history blocks. // -----------------------------------------------------------// ----------------------------------------------------------- // Current Success. // -----------------------------------------------------------// ----------------------------------------------------------- // Current Errors. // -----------------------------------------------------------// ----------------------------------------------------------- // Current Permissions. // ----------------------------------------------------------- /*** @apiDefine UnauthorizedError* @apiVersion 1.0.0** @apiError Unauthorized Only authenticated users can access the endpoint.** @apiErrorExample Unauthorized response:* HTTP 401 Unauthorized* {* "message": "Invalid credentials"* }*/// ----------------------------------------------------------- // History. // ----------------------------------------------------------- 復(fù)制代碼我還創(chuàng)建了另一個(gè)文件,也在 routes 目錄中,名為 apidoc.json
該文件包含以下內(nèi)容(示例):
{"name": "Test API - This is my API","version": "1.0.0","description": "This is my very powerful API","title": "Test API - This is my API","url": "https://testapi.com" } 復(fù)制代碼生成文檔時(shí),apiDoc 將會(huì)使用這兩個(gè)文件。
生成文檔
在為每個(gè)端點(diǎn)編寫注釋并配置好項(xiàng)目之后,我們需要配置一個(gè)任務(wù)來(lái)生成文檔。
我用 gulp 來(lái)做到這一切。安裝所需的依賴項(xiàng):
npm i gulp gulp-apidoc --save-dev 復(fù)制代碼然后在項(xiàng)目的根目錄中創(chuàng)建一個(gè)名為 gulpfile.js 的文件。如果它已經(jīng)存在,只需添加與 apiDoc 相關(guān)的部分:
const gulp = require("gulp"); const apidoc = require("gulp-apidoc");gulp.task("apidoc", (done) => {apidoc({src: "./routes",dest: "../docs/apidoc"}, done); });gulp.task("watch", () => {gulp.watch(["./routes/**"], ["apidoc"]); }); 復(fù)制代碼你可以將那里的 “dest” 目錄更改為另一個(gè)更適合你的目錄。這就是你希望生成輸出的位置。
現(xiàn)在你需要做的就是運(yùn)行:
gulp apidoc 復(fù)制代碼之后,你只需要在上面 “dest” 中配置的目錄中打開(kāi) index.html 文件,就會(huì)看到類似這樣的內(nèi)容):
其他開(kāi)發(fā)人員也可以用 gulp 生成相同的內(nèi)容,或者你??甚至可以通過(guò) Nginx 為生成的目錄提供Web服務(wù)。
總結(jié)
在這本文中,我們了解了如何使用注釋來(lái)記錄 API,并使用 apiDoc 為它們生成 HTML 格式的文檔。
你是否還用了其他軟件來(lái)為你的 API 生成文檔,或者你是否以其他方式使用 apiDoc?請(qǐng)?jiān)谙旅嬖u(píng)論中留言討論!
歡迎關(guān)注前端公眾號(hào):前端先鋒,獲取前端工程化實(shí)用工具包。
轉(zhuǎn)載于:https://juejin.im/post/5cef97cff265da1bc14b0d3e
總結(jié)
以上是生活随笔為你收集整理的使用 apiDoc 为你的Node.js API 生成文档的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 小程序和Android开发,微信小程序和
- 下一篇: 大学生集成电路设计大赛资源