您的位置:首页 > Web前端 > Node.js

使用 apiDoc 为你的Node.js API 自动生成文档[每日前端夜话0x78]

2021-02-02 07:32 1396 查看

使用 apiDoc 为你的Node.js API 自动生成文档[每日前端夜话0x78]

疯狂的技术宅 前端先锋

每日前端夜话0x78
每日前端夜话,陪你聊前端。
每天晚上18:00准时推送。
正文共:1511 字
预计阅读时间: 5 分钟
翻译:疯狂的技术宅
来源:jonathas

当你为其他开发人员(前端,桌面,移动等)开发 API 时,需要生成一份风格良好的文档,以便他们知道可以使用的内容和方式,这非常重要。

为此,在Node.js项目中,我一直在使用apiDoc【http://apidocjs.com/】,因为它能够从源代码中的注释生成HTML文档

对于本文,我将使用我开发的 TODO List API 作为示例。你可以从这里克隆或下载它【https://github.com/jonathas/todo-api】。

路由和注释

在我关于使用 mocha 进行测试并使用 istanbul 进行代码覆盖测试的文章中【https://jonathas.com/tests-and-code-coverage-on-node-using-typescript-with-mocha-and-istanbul/】,我在 TODO List API 中显示了 Task 端点的示例:

1import Task from "../controllers/tasks";
2
3export = (app) => {
4    const endpoint = process.env.API_BASE + "tasks";
5    app.post(endpoint, Task.create);
6    app.delete(endpoint + "/:id", Task.delete);
7    app.get(endpoint + "/:id", Task.getOne);
8    app.get(endpoint, Task.getAll);
9    app.put(endpoint + "/:id", Task.update);
10};

这代表了与系统中任务相关的所有端点。我们怎样才能使用它们呢?使用 API 的开发人员应该向每个端点发送什么数据呢?

到现在为止,他们除了去查看代码之外没有其他方法可以搞清楚,但是这些代码不应该被用作这个目的。

有了 apiDoc,我们可以用注释来生成文档。我的方法是在 routes 目录下的文件中配置的每个端点的前面编写它们。当我提到如何配置和组织我的 Node.js 项目时,如果你不确定我在说什么请 点击这里【https://jonathas.com/tests-and-code-coverage-on-node-using-typescript-with-mocha-and-istanbul/】。

使用注释,我们的任务端点(内部routes/tasks.ts)将如下所示:

1import Task from "../controllers/tasks";
2
3export = (app) => {
4
5    const endpoint = process.env.API_BASE + "tasks";
6
7    /**
8    * @api {post} /api/v1/tasks Create a task
9    * @apiVersion 1.0.0
10    * @apiName Create
11    * @apiGroup Task
12    * @apiPermission authenticated user
13    *
14    * @apiParam (Request body) {String} name The task name
15    *
16    * @apiExample {js} Example usage:
17    * const data = {
18    *   "name": "Do the dishes"
19    * }
20    *
21    * $http.defaults.headers.common["Authorization"] = token;
22    * $http.post(url, data)
23    *   .success((res, status) => doSomethingHere())
24    *   .error((err, status) => doSomethingHere());
25    *
26    * @apiSuccess (Success 201) {String} message Task saved successfully!
27    * @apiSuccess (Success 201) {String} id The campaign id
28    *
29    * @apiSuccessExample {json} Success response:
30    *     HTTPS 201 OK
31    *     {
32    *      "message": "Task saved successfully!",
33    *      "id": "57e903941ca43a5f0805ba5a"
34    *    }
35    *
36    * @apiUse UnauthorizedError
37    */
38    app.post(endpoint, Task.create);
39
40    /**
41    * @api {delete} /api/v1/tasks/:id Delete a task
42    * @apiVersion 1.0.0
43    * @apiName Delete
44    * @apiGroup Task
45    * @apiPermission authenticated user
46    *
47    * @apiParam {String} id The task id
48    *
49    * @apiExample {js} Example usage:
50    * $http.defaults.headers.common["Authorization"] = token;
51    * $http.delete(url)
52    *   .success((res, status) => doSomethingHere())
53    *   .error((err, status) => doSomethingHere());
54    *
55    * @apiSuccess {String} message Task deleted successfully!
56    *
57    * @apiSuccessExample {json} Success response:
58     *     HTTPS 200 OK
59     *     {
60     *      "message": "Task deleted successfully!"
61     *    }
62     *
63     * @apiUse UnauthorizedError
64    */
65    app.delete(endpoint + "/:id", Task.delete);
66
67    /**
68    * @api {get} /api/v1/tasks/:id Retrieve a task
69    * @apiVersion 1.0.0
70    * @apiName GetOne
71    * @apiGroup Task
72    * @apiPermission authenticated user
73    *
74    * @apiParam {String} id The task id
75    *
76    * @apiExample {js} Example usage:
77    * $http.defaults.headers.common["Authorization"] = token;
78    * $http.get(url)
79    *   .success((res, status) => doSomethingHere())
80    *   .error((err, status) => doSomethingHere());
81    *
82    * @apiSuccess {String} _id The task id
83    * @apiSuccess {String} name The task name
84    *
85    * @apiSuccessExample {json} Success response:
86     *     HTTPS 200 OK
87     *     {
88     *        "_id": "57e8e94ea06a0c473bac50cc",
89     *        "name": "Do the disehs",
90     *        "__v": 0
91     *      }
92     *
93     * @apiUse UnauthorizedError
94    */
95    app.get(endpoint + "/:id", Task.getOne);
96
97    /**
98    * @api {get} /api/v1/tasks Retrieve all tasks
99    * @apiVersion 1.0.0
100    * @apiName GetAll
101    * @apiGroup Task
102    * @apiPermission authenticated user
103    *
104    * @apiExample {js} Example usage:
105    * $http.defaults.headers.common["Authorization"] = token;
106    * $http.get(url)
107    *   .success((res, status) => doSomethingHere())
108    *   .error((err, status) => doSomethingHere());
109    *
110    * @apiSuccess {String} _id The task id
111    * @apiSuccess {String} name The task name
112    *
113    * @apiSuccessExample {json} Success response:
114    *     HTTPS 200 OK
115    *     [{
116    *       "_id": "57e8e94ea06a0c473bac50cc",
117    *       "name": "Do the disehs"
118    *      },
119    *      {
120    *       "_id": "57e903941ca43a5f0805ba5a",
121    *       "name": "Take out the trash"
122    *     }]
123    *
124    * @apiUse UnauthorizedError
125    */
126    app.get(endpoint, Task.getAll);
127
128    /**
129    * @api {put} /api/v1/tasks/:id Update a task
130    * @apiVersion 1.0.0
131    * @apiName Update
132    * @apiGroup Task
133    * @apiPermission authenticated user
134    *
135    * @apiParam {String} id The task id
136    *
137    * @apiParam (Request body) {String} name The task name
138    *
139    * @apiExample {js} Example usage:
140    * const data = {
141    *   "name": "Run in the park"
142    * }
143    *
144    * $http.defaults.headers.common["Authorization"] = token;
145    * $http.put(url, data)
146    *   .success((res, status) => doSomethingHere())
147    *   .error((err, status) => doSomethingHere());
148    *
149    * @apiSuccess {String} message Task updated successfully!
150    *
151    * @apiSuccessExample {json} Success response:
152     *     HTTPS 200 OK
153     *     {
154     *      "message": "Task updated successfully!"
155     *    }
156     *
157     * @apiUse UnauthorizedError
158    */
159    app.put(endpoint + "/:id", Task.update);
160
161};

如你所见,我们有 HTTP 方法的类型(post,put,get,delete)、端点地址、api 版本、它需要的权限类型、它需要的参数,还有如果用户是未经授权的应该返回怎样的响应和错误。

在官方网站【http://apidocjs.com/】中,你可以查看注释文档和可用参数

那么这个 UnauthorizedError 来自哪里呢?

apiDoc 设置

有一些设置可以用 apiDoc 完成,这个 UnauthorizedError 就是我经常要用到的。

在 routes 目录中创建一个名为 __apidoc.js 的文件,其中包含以下内容:

1// -----------------------------------------------------------
2// General apiDoc documentation blocks and old history blocks.
3// -----------------------------------------------------------
4
5// -----------------------------------------------------------
6// Current Success.
7// -----------------------------------------------------------
8
9
10// -----------------------------------------------------------
11// Current Errors.
12// -----------------------------------------------------------
13
14
15// -----------------------------------------------------------
16// Current Permissions.
17// -----------------------------------------------------------
18/**
19 * @apiDefine UnauthorizedError
20 * @apiVersion 1.0.0
21 *
22 * @apiError Unauthorized Only authenticated users can access the endpoint.
23 *
24 * @apiErrorExample  Unauthorized response:
25 *     HTTP 401 Unauthorized
26 *     {
27 *       "message": "Invalid credentials"
28 *     }
29 */
30
31// -----------------------------------------------------------
32// History.
33// -----------------------------------------------------------

我还创建了另一个文件,也在 routes 目录中,名为 apidoc.json

该文件包含以下内容(示例):

1{
2    "name": "Test API - This is my API",
3    "version": "1.0.0",
4    "description": "This is my very powerful API",
5    "title": "Test API - This is my API",
6    "url": "https://testapi.com"
7}

生成文档时,apiDoc 将会使用这两个文件。

生成文档

在为每个端点编写注释并配置好项目之后,我们需要配置一个任务来生成文档。

我用 gulp 来做到这一切。安装所需的依赖项:

1npm i gulp gulp-apidoc --save-dev

然后在项目的根目录中创建一个名为 gulpfile.js 的文件。如果它已经存在,只需添加与 apiDoc 相关的部分:

1const gulp = require("gulp");
2const apidoc = require("gulp-apidoc");
3
4gulp.task("apidoc", (done) => {
5    apidoc({
6        src: "./routes",
7        dest: "../docs/apidoc"
8    }, done);
9});
10
11gulp.task("watch", () => {
12    gulp.watch(["./routes/**"], ["apidoc"]);
13});

你可以将那里的 “dest” 目录更改为另一个更适合你的目录。这就是你希望生成输出的位置。

现在你需要做的就是运行:

1gulp apidoc

之后,你只需要在上面 “dest” 中配置的目录中打开 index.html 文件,就会看到类似这样的内容):

其他开发人员也可以用 gulp 生成相同的内容,或者你甚至可以通过 Nginx 为生成的目录提供Web服务。

总结

在这本文中,我们了解了如何使用注释来记录 API,并使用 apiDoc 为它们生成 HTML 格式的文档。

你是否还用了其他软件来为你的 API 生成文档,或者你是否以其他方式使用 apiDoc?请在下面评论中留言讨论!

原文:https://jonathas.com/documenting-your-nodejs-api-with-apidoc/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: