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

翻譯: 瘋狂的技術宅
原文: https://jonathas.com/document...

未經許可,禁止轉載!html


本文首發微信公衆號:前端先鋒
歡迎關注,天天都給你推送新鮮的前端技術文章前端


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

爲此,在Node.js項目中,我一直在使用apiDoc,由於它可以從源代碼中的註釋生成HTML文檔。git

對於本文,我將使用我開發的 TODO List API 做爲示例。你能夠從這裏克隆或下載它。程序員

路由和註釋

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

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 ​​的開發人員應該向每一個端點發送什麼數據呢?面試

到如今爲止,他們除了去查看代碼以外沒有其餘方法能夠搞清楚,可是這些代碼不該該被用做這個目的。typescript

有了 apiDoc,咱們能夠用註釋來生成文檔。個人方法是在 routes 目錄下的文件中配置的每一個端點的前面編寫它們。當我提到如何配置和組織個人 Node.js 項目時,若是你不肯定我在說什麼請 點擊這裏npm

使用註釋,咱們的任務端點(內部routes/tasks.ts)將以下所示:json

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?請在下面評論中留言討論!


本文首發微信公衆號:前端先鋒

歡迎掃描二維碼關注公衆號,天天都給你推送新鮮的前端技術文章

歡迎掃描二維碼關注公衆號,天天都給你推送新鮮的前端技術文章


歡迎繼續閱讀本專欄其它高贊文章:


相關文章
相關標籤/搜索