使用 apiDoc 為你的Node.js API 生成文檔

翻譯: 瘋狂的技術宅

原文:jonathas.com/documenting…

未經許可,禁止轉載!

當你為其他開發人員(前端,桌面,移動等)開發 API 時,需要生成一份風格良好的文檔,以便他們知道可以使用的內容和方式,這非常重要。

為此,在Node.js項目中,我一直在使用apiDoc,因為它能夠從源代碼中的注釋生成HTML文檔。

對于本文,我將使用我開發的 TODO List API 作為示例。你可以從這里克隆或下載它。

路由和注釋

在我關于使用 mocha 進行測試并使用 istanbul 進行代碼覆蓋測試的文章中,我在 TODO List API 中顯示了 Task 端點的示例:

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);
};
復制代碼

這代表了與系統中任務相關的所有端點。我們怎樣才能使用它們呢?使用 API ??的開發人員應該向每個端點發送什么數據呢?

到現在為止,他們除了去查看代碼之外沒有其他方法可以搞清楚,但是這些代碼不應該被用作這個目的。

有了 apiDoc,我們可以用注釋來生成文檔。我的方法是在 routes 目錄下的文件中配置的每個端點的前面編寫它們。當我提到如何配置和組織我的 Node.js 項目時,如果你不確定我在說什么請 點擊這里。

使用注釋,我們的任務端點(內部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);};
復制代碼

如你所見,我們有 HTTP 方法的類型(post,put,get,delete)、端點地址、api 版本、它需要的權限類型、它需要的參數,還有如果用戶是未經授權的應該返回怎樣的響應和錯誤。

在官方網站中,你可以查看注釋文檔和可用參數。

那么這個 UnauthorizedError 來自哪里呢?

apiDoc 設置

有一些設置可以用 apiDoc 完成,這個 UnauthorizedError 就是我經常要用到的。

在 routes 目錄中創建一個名為 __apidoc.js 的文件,其中包含以下內容:

// -----------------------------------------------------------
// 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.
// -----------------------------------------------------------
復制代碼

我還創建了另一個文件,也在 routes 目錄中,名為 apidoc.json

該文件包含以下內容(示例):

{"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"
}
復制代碼

生成文檔時,apiDoc 將會使用這兩個文件。

生成文檔

在為每個端點編寫注釋并配置好項目之后,我們需要配置一個任務來生成文檔。

我用 gulp 來做到這一切。安裝所需的依賴項:

npm i gulp gulp-apidoc --save-dev
復制代碼

然后在項目的根目錄中創建一個名為 gulpfile.js 的文件。如果它已經存在,只需添加與 apiDoc 相關的部分:

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"]);
});
復制代碼

你可以將那里的 “dest” 目錄更改為另一個更適合你的目錄。這就是你希望生成輸出的位置。

現在你需要做的就是運行:

gulp apidoc
復制代碼

之后,你只需要在上面 “dest” 中配置的目錄中打開 index.html 文件,就會看到類似這樣的內容):

其他開發人員也可以用 gulp 生成相同的內容,或者你??甚至可以通過 Nginx 為生成的目錄提供Web服務。

總結

在這本文中,我們了解了如何使用注釋來記錄 API,并使用 apiDoc 為它們生成 HTML 格式的文檔。

你是否還用了其他軟件來為你的 API 生成文檔,或者你是否以其他方式使用 apiDoc?請在下面評論中留言討論!

歡迎關注前端公眾號:前端先鋒,獲取前端工程化實用工具包。

轉載于:https://juejin.im/post/5cef97cff265da1bc14b0d3e

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/275052.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/275052.shtml
英文地址,請注明出處:http://en.pswp.cn/news/275052.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

海浪 shader_海浪下的發現

海浪 shaderI’ve been playing Subnautica for over 25 hours now, and likely have at least that many more to go. The game puts you in the shoes of a crew member on the Aurora, a spaceship that suffers a catastrophic incident and plummets to the largely ocean…

最后一天,特邀小姐姐配音拉票,今日可投28票

1源碼共讀大家好,我是若川。最后一天,特邀小姐姐配音拉票,超級好聽。眾所周知。從8月份開始,我組織了源碼共讀活動,至今已經有5個月了,每周一期,進行到了第18期。每周堅持寫源碼解讀文章&#x…

NET中使用Memcached的相關資源整理

本文轉自:http://www.cnblogs.com/dudu/archive/2009/07/19/1526407.html Memcached官方站點:http://www.danga.com/memcached / Memcached Win32 1.2.6下載:http://code.jellycan.com/memcached/ 安裝幫助:Windows下的.NET Memca…

FFMPEG 視頻圖像解封裝解碼

FFMPEG4.0 音頻解碼解封裝FFMPEG 音頻封裝編碼 下面的函數方法基于最新的FFMPEG 4.0(4.X):本文講是如何從一個視頻文件中提取出其中的圖像數據,并將圖像數據保存到文件中。 解碼解封裝的過程與音頻差不多,具體如下&…

對數據可視化的理解_使數據可視化更容易理解

對數據可視化的理解Data is weaving its way into almost all aspects of our lives since the past decade. Our ability to store more information in smaller and smaller spaces has encouraged us to make sure we leave no information out. The ease of collecting inf…

面試官:項目中常用的 .env 文件原理是什么?如何實現?

1. 前言大家好,我是若川。持續組織了5個月源碼共讀活動,感興趣的可以點此加我微信 ruochuan12 參與,每周大家一起學習200行左右的源碼,共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。本文倉庫 h…

語言分類,我接觸和我想學習的

本文信息和數據出自hyperpolyglot,將當前主流編程語言分為11個大類,分別為:解釋型(PHP,Perl,Python,Ruby,Tcl,Lua,JavaScript,Io)、操作系統自動化型(POSIX Shell,AppleScript,PowerShell)、C風格(C,Objective C,Java,C#)、Pascal風格(Pascal…

梯度下降法和隨機梯度下降法

1. 梯度 在微積分里面,對多元函數的參數求?偏導數,把求得的各個參數的偏導數以向量的形式寫出來,就是梯度。比如函數f(x,y), 分別對x,y求偏導數,求得的梯度向量就是(?f/?x, ?f/?y)T,簡稱grad f(x,y)或者▽f(x,y)。對于在點(x…

一張圖看程序媛阿源的2021個人年度流水賬

大家好,我是若川。持續組織了5個月源碼共讀活動,感興趣的可以點此加我微信 ruochuan12 參與,每周大家一起學習200行左右的源碼,共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。本文來自讀者阿源小…

案例研究:設計與方法_如何進行1小時的重新設計(案例研究)

案例研究:設計與方法速度設計簡介 (Intro to Speed Designing) I’ve been an advocate of speed redesigning technique for a while. The idea is simple — decrease the hand-eye lag and make super quick decisions, seemingly without thinking. The logic behind it is…

圖文并茂重新認識下遞歸

大家好,我是若川。持續組織了5個月源碼共讀活動,感興趣的可以點此加我微信 ruochuan12 參與,每周大家一起學習200行左右的源碼,共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。對于大部分前端(包…

《C和指針》讀書筆記

看過了經典的K&R C,又看了這本Pointers on C,溫習了C語言的基本語法。 在重溫過程中,感覺需要重點把握的知識是指針、結構和動態內存分配。 這對今后的算法和操作系統方面的研究學習很有幫助。 3.2.3 聲明指針int* b, c, d;本以為這條語句…

FPGA設計者的5項基本功

記得《佟林傳》里,佟林練的基本功是“繞大樹、解皮繩”,然后才練成了什么“鬼影隨行、柳葉綿絲掌”。 在我看來,成為一名說得過去的FPGA設計者,需要練好5項基本功:仿真、綜合、時序分析、調試、驗證。 需要強調的一點是…

unity 全息交互ui_UI向3D投影全息界面的連續發展

unity 全息交互uiThe user interface has been natural in its evolution and strategically heading towards the 3D-projection holographic interface (3D-PHI) era.用戶界面在其發展過程中一直很自然,并且在戰略上正朝著3D投影全息界面( 3D-PHI )時代邁進。 Si…

開發工具 快捷鍵整理

快捷鍵大全 JAVA 開發工具 MyEclipse -------------------------------------MyEclipse 快捷鍵1(CTRL)-------------------------------------Ctrl1 快速修復CtrlD: 刪除當前行 CtrlQ 定位到最后編輯的地方 CtrlL 定位在某行 CtrlO 快速顯示 OutLine CtrlT 快速顯示當前類…

前端構建新世代,Esbuild 原來還能這么玩!

大家好,我是若川。持續組織了5個月源碼共讀活動,感興趣的可以點此加我微信 ruochuan12 參與,每周大家一起學習200行左右的源碼,共同進步。同時極力推薦訂閱我寫的《學習源碼整體架構系列》 包含20余篇源碼文章。今天分享一篇esbui…

大三下學期十四周總結

在小組的學習方面,這周主要是對微信小程序的學習。對JSON格式請求在Spring boot與小程序之間的交互有了一些了解。對微信的接口wx.request、wx.uploadFile、wx.chooseImage的接口的使用。微信開發后臺傳過來的響應數據如果不是標準的json格式,需要在小程…

平面設計師和ui設計師_平面設計師為什么要享受所有樂趣?

平面設計師和ui設計師Graphic designers are pretty cool. We have to admit that. Be it their dressing style, their attitude and most importantly their enviable gadgets. Large Mac monitor, wacom tablet, drawing sets, swatchbooks , iPad pro with pencil, humungo…

轉:Xcode下的GDB調試命令

Xcode的調試器為用戶提供了一個GDB的圖形化界面,GDB是GNU組織的開放源代碼調試器。您可以在Xcode的圖形界面里做任何事情;但是,如果您需要您可以在命令行里使用GDB的命令,且gdb可以在終端運行,也可以在Xcode下的控制臺…

web表單設計:點石成金_設計復雜的用戶表單:12個UX最佳實踐

web表單設計:點石成金It’s been a few years that I’ve been taking interest in designing complex user forms, where a lot of information is requested from users. Here are a few industries where you regularly find such flows:幾年來,我一直對設計復雜…