├── .gitignore
├── .vscode
└── settings.json
├── LICENSE
├── README.md
└── docs
├── Benchmarking.md
├── ContentTypeParser.md
├── Contributing.md
├── Decorators.md
├── Encapsulation.md
├── Errors.md
├── Fluent-Schema.md
├── Getting-Started.md
├── HTTP2.md
├── Hooks.md
├── LTS.md
├── Lifecycle.md
├── Logging.md
├── Middleware.md
├── Migration-Guide-V3.md
├── Plugins-Guide.md
├── Plugins.md
├── Recommendations.md
├── Reply.md
├── Request.md
├── Routes.md
├── Server.md
├── Serverless.md
├── Testing.md
├── TypeScript.md
├── Validation-and-Serialization.md
├── Write-Plugin.md
└── resources
├── encapsulation_context.drawio
└── encapsulation_context.svg
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # next.js build output
61 | .next
62 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.formatOnSave": false
3 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Fastify
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Fastify 文档中文翻译
2 |
3 | ### 文档目录
4 | * [入门](https://github.com/fastify/docs-chinese/blob/main/docs/Getting-Started.md)
5 | * [服务器方法](https://github.com/fastify/docs-chinese/blob/main/docs/Server.md)
6 | * [路由](https://github.com/fastify/docs-chinese/blob/main/docs/Routes.md)
7 | * [日志](https://github.com/fastify/docs-chinese/blob/main/docs/Logging.md)
8 | * [中间件](https://github.com/fastify/docs-chinese/blob/main/docs/Middleware.md)
9 | * [钩子方法](https://github.com/fastify/docs-chinese/blob/main/docs/Hooks.md)
10 | * [装饰器](https://github.com/fastify/docs-chinese/blob/main/docs/Decorators.md)
11 | * [验证和序列化](https://github.com/fastify/docs-chinese/blob/main/docs/Validation-and-Serialization.md)
12 | * [生命周期](https://github.com/fastify/docs-chinese/blob/main/docs/Lifecycle.md)
13 | * [回复](https://github.com/fastify/docs-chinese/blob/main/docs/Reply.md)
14 | * [请求](https://github.com/fastify/docs-chinese/blob/main/docs/Request.md)
15 | * [错误](https://github.com/fastify/docs-chinese/blob/main/docs/Errors.md)
16 | * [Content-Type 解析](https://github.com/fastify/docs-chinese/blob/main/docs/ContentTypeParser.md)
17 | * [插件](https://github.com/fastify/docs-chinese/blob/main/docs/Plugins.md)
18 | * [测试](https://github.com/fastify/docs-chinese/blob/main/docs/Testing.md)
19 | * [基准测试](https://github.com/fastify/docs-chinese/blob/main/docs/Benchmarking.md)
20 | * [如何写一个好的插件](https://github.com/fastify/docs-chinese/blob/main/docs/Write-Plugin.md)
21 | * [插件指南](https://github.com/fastify/docs-chinese/blob/main/docs/Plugins-Guide.md)
22 | * [HTTP2](https://github.com/fastify/docs-chinese/blob/main/docs/HTTP2.md)
23 | * [长期支持计划](https://github.com/fastify/docs-chinese/blob/main/docs/LTS.md)
24 | * [TypeScript 与类型支持](https://github.com/fastify/docs-chinese/blob/main/docs/TypeScript.md)
25 | * [Serverless](https://github.com/fastify/docs-chinese/blob/main/docs/Serverless.md)
26 | * [推荐方案](https://github.com/fastify/docs-chinese/blob/main/docs/Recommendations.md)
27 |
28 | ### 其他版本
29 |
30 | * [v2.x](https://github.com/fastify/docs-chinese/tree/2.x)
31 |
32 | ### 翻译指南
33 |
34 | 想要参与到项目当中?欢迎!
35 | 为了提供一致的翻译体验,请在开始翻译前参阅[翻译指南](https://github.com/fastify/docs-chinese/blob/main/docs/Contributing.md)。感谢!
36 |
37 | ### 贡献者
38 | * [@fralonra](https://github.com/fralonra)
39 | * [@poppinlp](https://github.com/poppinlp)
40 | * [@vincent178](https://github.com/vincent178)
41 | * [@xtx1130](https://github.com/xtx1130)
42 |
--------------------------------------------------------------------------------
/docs/Benchmarking.md:
--------------------------------------------------------------------------------
1 |
Fastify
2 |
3 | ## 基准测试
4 | 基准测试对于衡量改动可能引起的性能变化很重要. 从用户和贡献者的角度, 我们提供了简便的方法测试你的应用. 这套配置可以自动化你的基准测试, 从不同的分支和不同的 Node.js 的版本.
5 |
6 | 我们将使用以下模块:
7 | - [Autocannon](https://github.com/mcollina/autocannon): 用 Node 写的 HTTP/1.1 基准测试工具.
8 | - [Branch-comparer](https://github.com/StarpTech/branch-comparer): 切换不同的 git 分支, 执行脚本并记录结果.
9 | - [Concurrently](https://github.com/kimmobrunfeldt/concurrently): 并行运行命令.
10 | - [Npx](https://github.com/npm/npx): NPM 包运行器,用于在不同的 Node.js 版本上执行运行脚本和运行本地的二进制文件. 在 npm@5.2.0 版本以上可用.
11 |
12 | ## 基本用法
13 |
14 | ### 在当前分支上运行测试
15 | ```sh
16 | npm run benchmark
17 | ```
18 |
19 | ### 在不同的 Node.js 版本中运行测试 ✨
20 | ```sh
21 | npx -p node@6 -- npm run benchmark
22 | ```
23 |
24 | ## 进阶用法
25 |
26 | ### 在不同的分支上运行测试
27 | ```sh
28 | branchcmp --rounds 2 --script "npm run benchmark"
29 | ```
30 |
31 | ### 在不同的分支和不同的 Node.js 版本中运行测试 ✨
32 | ```sh
33 | branchcmp --rounds 2 --script "npm run benchmark"
34 | ```
35 |
36 | ### 比较当前的分支和主分支 (Gitflow)
37 | ```sh
38 | branchcmp --rounds 2 --gitflow --script "npm run benchmark"
39 | ```
40 | or
41 | ```sh
42 | npm run bench
43 | ```
44 |
45 | ### 运行不同的用例
46 |
47 | ```sh
48 | branchcmp --rounds 2 -s "node ./node_modules/concurrently -k -s first \"node ./examples/asyncawait.js\" \"node ./node_modules/autocannon -c 100 -d 5 -p 10 localhost:3000/\""
49 | ```
50 |
--------------------------------------------------------------------------------
/docs/ContentTypeParser.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## `Content-Type` 解析
4 | Fastify 原生只支持 `'application/json'` 和 `'text/plain'` content type。默认的字符集是 `utf-8`。如果你需要支持其他的 content type,你需要使用 `addContentTypeParser` API。*默认的 JSON 或者纯文本解析器也可以被更改或删除。*
5 |
6 | *注:假如你决定用 `Content-Type` 自定义 content type,UTF-8 便不再是默认的字符集了。请确保如下包含该字符集:`text/html; charset=utf-8`。*
7 |
8 | 和其他的 API 一样,`addContentTypeParser` 被封装在定义它的作用域中了。这就意味着如果你定义在了根作用域中,那么就是全局可用,如果你定义在一个插件中,那么它只能在那个作用域和子作用域中可用。
9 |
10 | Fastify 自动将解析好的 payload 添加到 [Fastify request](Request.md) 对象,你能通过 `request.body` 访问。
11 |
12 | ### 用法
13 | ```js
14 | fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
15 | jsoffParser(payload, function (err, body) {
16 | done(err, body)
17 | })
18 | })
19 |
20 | // 以相同方式处理多种 content type
21 | fastify.addContentTypeParser(['text/xml', 'application/xml'], function (request, payload, done) {
22 | xmlParser(payload, function (err, body) {
23 | done(err, body)
24 | })
25 | })
26 |
27 | // Node 版本 >= 8.0.0 时也支持 async
28 | fastify.addContentTypeParser('application/jsoff', async function (request, payload) {
29 | var res = await jsoffParserAsync(payload)
30 |
31 | return res
32 | })
33 |
34 | // 处理所有匹配的 content type
35 | fastify.addContentTypeParser(/^image\/.*/, function (request, payload, done) {
36 | imageParser(payload, function (err, body) {
37 | done(err, body)
38 | })
39 | })
40 |
41 | // 可以为不同的 content type 使用默认的 JSON/Text 解析器
42 | fastify.addContentTypeParser('text/json', { parseAs: 'string' }, fastify.getDefaultJsonParser('ignore', 'ignore'))
43 | ```
44 |
45 | 在使用正则匹配 content-type 解析器之前,Fastify 首先会查找解析出 `string` 类型值的解析器。假如提供了重复的类型,那么 Fastify 会按照提供的顺序反向查找。因此,你可以先指定一般的 content type,之后再指定更为特殊的类型,正如下面的例子一样。
46 |
47 | ```js
48 | // 只会调用第二个解析器,因为它也匹配了第一个解析器的类型
49 | fastify.addContentTypeParser('application/vnd.custom+xml', (request, body, done) => {} )
50 | fastify.addContentTypeParser('application/vnd.custom', (request, body, done) => {} )
51 |
52 | // 这才是我们期望的行为。因为 Fastify 会首先尝试匹配 `application/vnd.custom+xml` content type 解析器
53 | fastify.addContentTypeParser('application/vnd.custom', (request, body, done) => {} )
54 | fastify.addContentTypeParser('application/vnd.custom+xml', (request, body, done) => {} )
55 | ```
56 |
57 | 在 `hasContentTypeParser` 之外,还有其他 API 可供使用,它们是:`hasContentTypeParser`、`removeContentTypeParser` 与 `removeAllContentTypeParsers`。
58 |
59 | #### hasContentTypeParser
60 |
61 | 使用 `hasContentTypeParser` API 来查询是否存在特定的 content type 解析器。
62 |
63 | ```js
64 | if (!fastify.hasContentTypeParser('application/jsoff')){
65 | fastify.addContentTypeParser('application/jsoff', function (request, payload, done) {
66 | jsoffParser(payload, function (err, body) {
67 | done(err, body)
68 | })
69 | })
70 | }
71 | ```
72 |
73 | #### removeContentTypeParser
74 |
75 | 通过 `removeContentTypeParser` 可移除一个或多个 content type 解析器。支持使用 `string` 或
76 | `RegExp` 来匹配。
77 |
78 | ```js
79 | fastify.addContentTypeParser('text/xml', function (request, payload, done) {
80 | xmlParser(payload, function (err, body) {
81 | done(err, body)
82 | })
83 | })
84 |
85 | // 移除内建的 content type 解析器。这时只有上文添加的 text/html 解析器可用。
86 | Fastiy.removeContentTypeParser(['application/json', 'text/plain'])
87 | ```
88 |
89 | #### removeAllContentTypeParsers
90 |
91 | 在上文的例子中,你需要明确指定所有你想移除的 content type。但你也可以使用 `removeAllContentTypeParsers`直接移除所有现存的 content type 解析器。在下面的例子里,我们实现了一样的效果,但不再需要手动指定 content type 了。和 `removeContentTypeParser` 一样,该 API 也支持封装。当你想注册一个[能捕获所有 content type 的解析器](#Catch-All),且忽略内建的解析器时,这个 API 特别有用。
92 |
93 | ```js
94 | Fastiy.removeAllContentTypeParsers()
95 |
96 | fastify.addContentTypeParser('text/xml', function (request, payload, done) {
97 | xmlParser(payload, function (err, body) {
98 | done(err, body)
99 | })
100 | })
101 | ```
102 |
103 | **注意**:早先的写法 `function(req, done)` 与 `async function(req)` 仍被支持,但不推荐使用。
104 |
105 | #### Body Parser
106 |
107 | 你可以用两种方式解析消息主体。第一种方法在上面演示过了: 你可以添加定制的 content type 解析器来处理请求。第二种方法你可以在 `addContentTypeParser` API 传递 `parseAs` 参数。它可以是 `'string'` 或者 `'buffer'`。如果你使用 `parseAs` 选项 Fastify 会处理 stream 并且进行一些检查,比如消息主体的 [最大尺寸](Factory.md#factory-body-limit) 和消息主体的长度。如果达到了某些限制,自定义的解析器就不会被调用。
108 |
109 | ```js
110 | fastify.addContentTypeParser('application/json', { parseAs: 'string' }, function (req, body, done) {
111 | try {
112 | var json = JSON.parse(body)
113 | done(null, json)
114 | } catch (err) {
115 | err.statusCode = 400
116 | done(err, undefined)
117 | }
118 | })
119 | ```
120 |
121 | 查看例子 [`example/parser.js`](https://github.com/fastify/fastify/blob/main/examples/parser.js)。
122 |
123 | ##### 自定义解析器的选项
124 | + `parseAs` (string): `'string'` 或者 `'buffer'` 定义了如何收集进来的数据。默认是 `'buffer'`。
125 | + `bodyLimit` (number): 自定义解析器能够接收的最大的数据长度,比特为单位。默认是全局的消息主体的长度限制[`Fastify 工厂方法`](Factory.md#bodylimit)。
126 |
127 | #### 捕获所有
128 |
129 | 有些情况下你需要捕获所有的 content type。通过 Fastify,你只需添加`'*'` content type。
130 |
131 | ```js
132 | fastify.addContentTypeParser('*', function (request, payload, done) {
133 | var data = ''
134 | payload.on('data', chunk => { data += chunk })
135 | payload.on('end', () => {
136 | done(null, data)
137 | })
138 | })
139 | ```
140 |
141 | 在这种情况下,所有的没有特定 content type 解析器的请求都会被这个方法处理。
142 |
143 | 对请求流 (stream) 执行管道输送 (pipe) 操作也是有用的。你可以如下定义一个 content 解析器:
144 |
145 | ```js
146 | fastify.addContentTypeParser('*', function (request, payload, done) {
147 | done()
148 | })
149 | ```
150 |
151 | 之后通过核心 HTTP request 对象将请求流直接输送到任意位置:
152 |
153 | ```js
154 | app.post('/hello', (request, reply) => {
155 | reply.send(request.raw)
156 | })
157 | ```
158 |
159 | 这里有一个将来访的 [json line](https://jsonlines.org/) 对象完整输出到日志的例子:
160 |
161 | ```js
162 | const split2 = require('split2')
163 | const pump = require('pump')
164 |
165 | fastify.addContentTypeParser('*', (request, payload, done) => {
166 | done(null, pump(payload, split2(JSON.parse)))
167 | })
168 |
169 | fastify.route({
170 | method: 'POST',
171 | url: '/api/log/jsons',
172 | handler: (req, res) => {
173 | req.body.on('data', d => console.log(d)) // 记录每个来访的对象
174 | }
175 | })
176 | ```
177 |
178 | 关于处理上传的文件,请看[该插件](https://github.com/fastify/fastify-multipart)。
179 |
180 | 如果你真的想将某解析器用于所有 content type,而不仅用于缺少具体解析器的 content type,你应该先调用 `removeAllContentTypeParsers` 方法。
181 |
182 | ```js
183 | // 没有下面这行的话,content type 为 application/json 的 body 将被内建的 json 解析器处理。
184 | fastify.removeAllContentTypeParsers()
185 |
186 | fastify.addContentTypeParser('*', function (request, payload, done) {
187 | var data = ''
188 | payload.on('data', chunk => { data += chunk })
189 | payload.on('end', () => {
190 | done(null, data)
191 | })
192 | })
193 | ```
--------------------------------------------------------------------------------
/docs/Contributing.md:
--------------------------------------------------------------------------------
1 | ## 翻译指南
2 |
3 | 如果你发现了翻译的错误,或文档的滞后,请创建一个 issue 来告诉我们,或是按如下方法直接参与翻译。感谢!
4 |
5 | * Fork https://github.com/fastify/docs-chinese
6 | * 创建 Git Branch
7 | * 开始翻译
8 | * 创建 PR,尽量保证一篇文档一个 commit 一个 PR
9 |
10 | ### 风格规范
11 |
12 | 为了保证翻译风格的统一,请按照如下规范进行翻译。
13 | 你可以在[这里](https://github.com/fastify/docs-chinese/issues/66)一起参与规范的讨论。
14 |
15 | - 所有翻译的文本内容采用 markdown 编写,支持 GMF,不熟悉的话可以参考如下链接:
16 | - https://help.github.com/articles/getting-started-with-writing-and-formatting-on-github/
17 | - https://help.github.com/categories/writing-on-github/
18 | - 中文与英文之间需要加一个空格,例如 `你好 hello 你好`
19 | - 中文与数字之间需要加一个空格,例如 `2018 年 12 月 20 日`
20 | - 正文中的英文标点需要转换为对应的中文标点,例如 `,` => `,`
21 | - 例外:英文括号修改为半角括号加一个空格的形式,例如 `()` => ` () `
22 | - 注意:英文逗号可能需要转换为中文顿号,而非中文逗号
23 | - 代码片段中的注释需要翻译
24 | - 不做翻译的内容:
25 | - 常见的缩写内容,例如 `UI`, `HTTP`
26 | - 常见的框架、平台、语言等,例如 `Express`, `Node`, `Java`
27 | - 用于表示工程代码中的一些实例,例如 `Promise`, Node 中的 `Request`
28 | - 对于可能产生误解的名词翻译,如果在术语表中有,请按照对应的内容做翻译;如果术语表中未出现,那么推荐翻译后括号注解原文,例如 `运行时(Runtime)`
29 |
--------------------------------------------------------------------------------
/docs/Decorators.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 装饰器
4 |
5 | 装饰器 API 允许你自定义服务器实例或请求周期中的请求/回复等对象。任意类型的属性都能通过装饰器添加到这些对象上,包括函数、普通对象 (plain object) 以及原生类型。
6 |
7 | 装饰器 API 是 *同步* 的。如果异步地添加装饰器,可能会导致在装饰器完成初始化之前, Fastify 实例就已经引导完毕了。因此,必须将 `register` 方法与 `fastify-plugin` 结合使用。详见 [Plugins](Plugins.md)。
8 |
9 | 通过装饰器 API 来自定义对象,底层的 Javascript 引擎便能对其进行优化。这是因为引擎能在所有的对象实例被初始化与使用前,定义好它们的形状 (shape)。下文的例子则是不推荐的做法,因为它在对象的生命周期中修改了它们的形状:
10 |
11 | ```js
12 | // 不推荐的写法!请继续阅读。
13 |
14 | // 在调用请求处理函数之前
15 | // 将 user 属性添加到请求上。
16 | fastify.addHook('preHandler', function (req, reply, done) {
17 | req.user = 'Bob Dylan'
18 | done()
19 | })
20 |
21 | // 在处理函数中使用 user 属性。
22 | fastify.get('/', function (req, reply) {
23 | reply.send(`Hello, ${req.user}`)
24 | })
25 | ```
26 |
27 | 由于上述例子在请求对象初始化完成后,还改动了它的形状,因此 JavaScript 引擎必须对该对象去优化。使用装饰器 API 能避开去优化问题:
28 |
29 | ```js
30 | // 使用装饰器为请求对象添加 'user' 属性。
31 | fastify.decorateRequest('user', '')
32 |
33 | // 更新属性。
34 | fastify.addHook('preHandler', (req, reply, done) => {
35 | req.user = 'Bob Dylan'
36 | done()
37 | })
38 | // 最后访问它。
39 | fastify.get('/', (req, reply) => {
40 | reply.send(`Hello, ${req.user}!`)
41 | })
42 | ```
43 |
44 | 装饰器的初始值应该尽可能地与其未来将被设置的值接近。例如,字符串类型的装饰器的初始值为 `''`,对象或函数类型的初始值为 `null`。
45 |
46 | 请注意,上述例子仅可用于基本类型的值,因为引用类型会在所有请求中共享。详见 [decorateRequest](#decorate-request)。
47 |
48 | 更多此话题的内容,请见 [JavaScript engine fundamentals: Shapes and Inline Caches](https://mathiasbynens.be/notes/shapes-ics)。
49 |
50 | ### 使用方法
51 |
52 |
53 | #### `decorate(name, value, [dependencies])`
54 |
55 |
56 | 该方法用于自定义 Fastify [server](Server.md) 实例。
57 |
58 | 例如,为其添加一个新方法:
59 |
60 | ```js
61 | fastify.decorate('utility', function () {
62 | // 新功能的代码
63 | })
64 | ```
65 |
66 | 正如上文所述,还可以传递非函数的值:
67 |
68 | ```js
69 | fastify.decorate('conf', {
70 | db: 'some.db',
71 | port: 3000
72 | })
73 | ```
74 |
75 | 通过装饰属性的名称便可访问值:
76 |
77 | ```js
78 | fastify.utility()
79 |
80 | console.log(fastify.conf.db)
81 | ```
82 |
83 | [路由](Routes.md)函数的 `this` 指向 [Fastify server](Server.md):
84 |
85 | ```js
86 | fastify.decorate('db', new DbConnection())
87 |
88 | fastify.get('/', async function (request, reply) {
89 | reply({hello: await this.db.query('world')})
90 | })
91 | ```
92 |
93 | 可选的 `dependencies` 参数用于指定当前装饰器所依赖的其他装饰器列表。这个列表包含了其他装饰器的名称字符串。在下面的例子里,装饰器 "utility" 依赖于 "greet" 和 "log":
94 |
95 | ```js
96 | fastify.decorate('utility', fn, ['greet', 'log'])
97 | ```
98 |
99 | 注:使用箭头函数会破坏 `FastifyInstance` 的 `this` 绑定。
100 |
101 | 一旦有依赖项不满足,`decorate` 方法便会抛出异常。依赖项检查是在服务器实例启动前进行的,因此,在运行时不会发生异常。
102 |
103 | #### `decorateReply(name, value, [dependencies])`
104 |
105 |
106 | 顾名思义,`decorateReply` 向 `Reply` 核心对象添加新的方法或属性:
107 |
108 | ```js
109 | fastify.decorateReply('utility', function () {
110 | // 新功能的代码
111 | })
112 | ```
113 |
114 | 注:使用箭头函数会破坏 `this` 和 Fastify `Reply` 实例的绑定。
115 |
116 | 注:使用 `decorateReply` 装饰引用类型,会触发警示:
117 |
118 | ```js
119 | // 反面教材
120 | fastify.decorateReply('foo', { bar: 'fizz'})
121 | ```
122 | 在这个例子里,该对象的引用存在于所有请求中,导致**任何更改都会影响到所有请求,并可能触发安全漏洞或内存泄露**。要合适地封装请求对象,请在 [`'onRequest'` 钩子](Hooks.md#onrequest)里设置新的值。示例如下:
123 |
124 | ```js
125 | const fp = require('fastify-plugin')
126 |
127 | async function myPlugin (app) {
128 | app.decorateRequest('foo', null)
129 | app.addHook('onRequest', async (req, reply) => {
130 | req.foo = { bar: 42 }
131 | })
132 | }
133 |
134 | module.exports = fp(myPlugin)
135 | ```
136 |
137 | 关于 `dependencies` 参数,请见 [`decorate`](#decorate)。
138 |
139 | #### `decorateRequest(name, value, [dependencies])`
140 |
141 |
142 | 同理,`decorateRequest` 向 `Request` 核心对象添加新的方法或属性:
143 |
144 | ```js
145 | fastify.decorateRequest('utility', function () {
146 | // 新功能的代码
147 | })
148 | ```
149 |
150 | 注:使用箭头函数会破坏 `this` 和 Fastify `Request` 实例的绑定。
151 |
152 | 注:使用 `decorateRequest` 装饰引用类型,会触发警示:
153 |
154 | ```js
155 | // 反面教材
156 | fastify.decorateRequest('foo', { bar: 'fizz'})
157 | ```
158 | 在这个例子里,该对象的引用存在于所有请求中,导致**任何更改都会影响到所有请求,并可能触发安全漏洞或内存泄露**。要合适地封装请求对象,请在 [`'onRequest'` 钩子](Hooks.md#onrequest)里设置新的值。示例如下:
159 |
160 | ```js
161 | const fp = require('fastify-plugin')
162 |
163 | async function myPlugin (app) {
164 | app.decorateRequest('foo', null)
165 | app.addHook('onRequest', async (req, reply) => {
166 | req.foo = { bar: 42 }
167 | })
168 | }
169 |
170 | module.exports = fp(myPlugin)
171 | ```
172 |
173 | 关于 `dependencies` 参数,请见 [`decorate`](#decorate)。
174 |
175 | #### `hasDecorator(name)`
176 |
177 |
178 | 用于检查服务器实例上是否存在某个装饰器:
179 |
180 | ```js
181 | fastify.hasDecorator('utility')
182 | ```
183 |
184 | #### hasRequestDecorator
185 |
186 |
187 | 用于检查 Request 实例上是否存在某个装饰器:
188 |
189 | ```js
190 | fastify.hasRequestDecorator('utility')
191 | ```
192 |
193 | #### hasReplyDecorator
194 |
195 |
196 | 用于检查 Reply 实例上是否存在某个装饰器:
197 |
198 | ```js
199 | fastify.hasReplyDecorator('utility')
200 | ```
201 |
202 | ### 装饰器与封装
203 |
204 |
205 | 在 **封装** 的同一个上下文中,如果通过 `decorate`、`decorateRequest` 以及 `decorateReply` 多次定义了一个同名的的装饰器,将会抛出一个异常。
206 |
207 | 下面的示例会抛出异常:
208 | ```js
209 | const server = require('fastify')()
210 | server.decorateReply('view', function (template, args) {
211 | // 页面渲染引擎的代码。
212 | })
213 | server.get('/', (req, reply) => {
214 | reply.view('/index.html', { hello: 'world' })
215 | })
216 | // 当在其他地方定义
217 | // view 装饰器时,抛出异常。
218 | server.decorateReply('view', function (template, args) {
219 | // 另一个渲染引擎。
220 | })
221 | server.listen(3000)
222 | ```
223 |
224 | 但下面这个例子不会抛异常:
225 |
226 | ```js
227 | const server = require('fastify')()
228 | server.decorateReply('view', function (template, args) {
229 | // 页面渲染引擎的代码。
230 | })
231 | server.register(async function (server, opts) {
232 | // 我们在当前封装的插件内添加了一个 view 装饰器。
233 | // 这么做不会抛出异常。
234 | // 因为插件外部和内部的 view 装饰器是不一样的。
235 | server.decorateReply('view', function (template, args) {
236 | // another rendering engine
237 | })
238 | server.get('/', (req, reply) => {
239 | reply.view('/index.page', { hello: 'world' })
240 | })
241 | }, { prefix: '/bar' })
242 | server.listen(3000)
243 | ```
244 |
245 | ### Getter 和 Setter
246 |
247 |
248 | 装饰器接受特别的 "getter/setter" 对象。这些对象拥有着名为 `getter` 与 `setter` 的函数 (尽管 `setter` 是可选的)。这么做便可以通过装饰器来定义属性。例如:
249 |
250 | ```js
251 | fastify.decorate('foo', {
252 | getter () {
253 | return 'a getter'
254 | }
255 | })
256 | ```
257 |
258 | 上例会在 Fastify 实例中定义一个 `foo` 属性:
259 |
260 | ```js
261 | console.log(fastify.foo) // 'a getter'
262 | ```
263 |
--------------------------------------------------------------------------------
/docs/Encapsulation.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 |
4 | ## 封装
5 |
6 | “封装上下文”是 Fastify 的一个基础特性,负责控制[路由](./Routes.md)能访问的[装饰器](./Decorators.md)、[钩子](./Hooks.md)以及[插件](./Plugins.md)。下图是封装上下文的抽象表现:
7 |
8 | 
9 |
10 | 上图可归纳为以下几块内容:
11 |
12 | 1. _顶层上下文 (root context)_
13 | 2. 三个 _顶层插件 (root plugin)_
14 | 3. 两个 _子上下文 (child context)_,每个 _子上下文_ 拥有
15 | * 两个 _子插件 (child plugin)_
16 | * 一个 _孙子上下文 (grandchild context)_,其又拥有
17 | - 三个 _子插件 (child plugin)_
18 |
19 | 任意 _子上下文_ 或 _孙子上下文_ 都有权访问 _顶层插件_。_孙子上下文_ 有权访问它上级的 _子上下文_ 中注册的 _子插件_,但 _子上下文_ *无权* 访问它下级的 _孙子上下文中_ 注册的 _子插件_。
20 |
21 | 在 Fastify 中,除了 _顶层上下文_,一切皆为[插件](./Plugins.md)。下文的例子也不例外,所有的“上下文”和“插件”都是包含装饰器、钩子、插件及路由的插件。该例子为有三个路由的 REST API 服务器,第一个路由 (`/one`) 需要鉴权 (使用 [fastify-bearer-auth][bearer]),第二个路由 (`/two`) 无需鉴权,第三个路由 (`/three`) 有权访问第二个路由的上下文:
22 |
23 | ```js
24 | 'use strict'
25 |
26 | const fastify = require('fastify')()
27 |
28 | fastify.decorateRequest('answer', 42)
29 |
30 | fastify.register(async function authenticatedContext (childServer) {
31 | childServer.register(require('fastify-bearer-auth'), { keys: ['abc123'] })
32 |
33 | childServer.route({
34 | path: '/one',
35 | method: 'GET',
36 | handler (request, response) {
37 | response.send({
38 | answer: request.answer,
39 | // request.foo 会是 undefined,因为该值是在 publicContext 中定义的
40 | foo: request.foo,
41 | // request.bar 会是 undefined,因为该值是在 grandchildContext 中定义的
42 | bar: request.bar
43 | })
44 | }
45 | })
46 | })
47 |
48 | fastify.register(async function publicContext (childServer) {
49 | childServer.decorateRequest('foo', 'foo')
50 |
51 | childServer.route({
52 | path: '/two',
53 | method: 'GET',
54 | handler (request, response) {
55 | response.send({
56 | answer: request.answer,
57 | foo: request.foo,
58 | // request.bar 会是 undefined,因为该值是在 grandchildContext 中定义的
59 | bar: request.bar
60 | })
61 | }
62 | })
63 |
64 | childServer.register(async function grandchildContext (grandchildServer) {
65 | grandchildServer.decorateRequest('bar', 'bar')
66 |
67 | grandchildServer.route({
68 | path: '/three',
69 | method: 'GET',
70 | handler (request, response) {
71 | response.send({
72 | answer: request.answer,
73 | foo: request.foo,
74 | bar: request.bar
75 | })
76 | }
77 | })
78 | })
79 | })
80 |
81 | fastify.listen(8000)
82 | ```
83 |
84 | 上面的例子展示了所有封装相关的概念:
85 |
86 | 1. 每个 _子上下文_ (`authenticatedContext`、`publicContext` 及 `grandchildContext`) 都有权访问在 _顶层上下文_ 中定义的 `answer` 请求装饰器。
87 | 2. 只有 `authenticatedContext` 能访问 `fastify-bearer-auth` 插件。
88 | 3. `publicContext` 和 `grandchildContext` 都能访问 `foo` 请求装饰器。
89 | 4. 只有 `grandchildContext` 能访问 `bar` 请求装饰器。
90 |
91 | 启动服务来验证这些概念吧:
92 |
93 | ```sh
94 | # curl -H 'authorization: Bearer abc123' http://127.0.0.1:8000/one
95 | {"answer":42}
96 | # curl http://127.0.0.1:8000/two
97 | {"answer":42,"foo":"foo"}
98 | # curl http://127.0.0.1:8000/three
99 | {"answer":42,"foo":"foo","bar":"bar"}
100 | ```
101 |
102 | [bearer]: https://github.com/fastify/fastify-bearer-auth
103 |
104 |
105 | ## 在上下文间共享
106 |
107 | 请注意,在上文例子中,每个上下文都 _仅_ 从父级上下文进行继承,而父级上下文无权访问后代上下文中定义的实体。在某些情况下,我们并不想要这一默认行为。使用 [fastify-plugin][fastify-plugin] ,便能允许父级上下文访问到后代上下文中定义的实体。
108 |
109 | 假设上例的 `publicContext` 需要获取 `grandchildContext` 中定义的 `bar` 装饰器,我们可以重写代码如下:
110 |
111 | ```js
112 | 'use strict'
113 |
114 | const fastify = require('fastify')()
115 | const fastifyPlugin = require('fastify-plugin')
116 |
117 | fastify.decorateRequest('answer', 42)
118 |
119 | // 为了代码清晰,这里省略了 `authenticatedContext`
120 |
121 | fastify.register(async function publicContext (childServer) {
122 | childServer.decorateRequest('foo', 'foo')
123 |
124 | childServer.route({
125 | path: '/two',
126 | method: 'GET',
127 | handler (request, response) {
128 | response.send({
129 | answer: request.answer,
130 | foo: request.foo,
131 | bar: request.bar
132 | })
133 | }
134 | })
135 |
136 | childServer.register(fastifyPlugin(grandchildContext))
137 |
138 | async function grandchildContext (grandchildServer) {
139 | grandchildServer.decorateRequest('bar', 'bar')
140 |
141 | grandchildServer.route({
142 | path: '/three',
143 | method: 'GET',
144 | handler (request, response) {
145 | response.send({
146 | answer: request.answer,
147 | foo: request.foo,
148 | bar: request.bar
149 | })
150 | }
151 | })
152 | }
153 | })
154 |
155 | fastify.listen(8000)
156 | ```
157 |
158 | 重启服务,访问 `/two` 和 `/three` 路由:
159 |
160 | ```sh
161 | # curl http://127.0.0.1:8000/two
162 | {"answer":42,"foo":"foo","bar":"bar"}
163 | # curl http://127.0.0.1:8000/three
164 | {"answer":42,"foo":"foo","bar":"bar"}
165 | ```
166 |
167 | [fastify-plugin]: https://github.com/fastify/fastify-plugin
--------------------------------------------------------------------------------
/docs/Errors.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 |
4 | ## 错误
5 |
6 |
7 | ### Node.js 错误处理
8 |
9 | #### 未捕获的错误
10 | 在 Node.js 里,未捕获的错误容易引起内存泄漏、文件描述符泄漏等生产环境主要的问题。[Domain 模块](https://nodejs.org/en/docs/guides/domain-postmortem/)被设计用来解决这一问题,然而效果不佳。
11 |
12 | 由于不可能合理地处理所有未捕获的错误,目前最好的处理方案就是[使程序崩溃](https://nodejs.org/api/process.html#process_warning_using_uncaughtexception_correctly)。
13 |
14 | #### 在 Promise 里捕获错误
15 | 未处理的 promise rejection (即未被 `.catch()` 处理) 在 Node.js 中也可能引起内存或文件描述符泄漏。`unhandledRejection` 不被推荐,未处理的 rejection 也不会抛出,因此还是可能会泄露。你应当使用如 [`make-promises-safe`](https://github.com/mcollina/make-promises-safe) 的模块来确保未处理的 rejection _总能_ 被抛出。
16 |
17 | 假如你使用 promise,你应当同时给它们加上 `.catch()`。
18 |
19 | ### Fastify 的错误
20 | Fastify 遵循不全则无的原则,旨在精而优。因此,确保正确处理错误是开发者需要考虑的问题。
21 |
22 | #### 输入数据的错误
23 | 由于大部分的错误源于预期外的输入,因此我们推荐[通过 JSON.schema 来验证输入数据](Validation-and-Serialization.md)。
24 |
25 | #### 在 Fastify 中捕捉未捕获的错误
26 | 在不影响性能的前提下,Fastify 尽可能多地捕捉未捕获的错误。这些错误包括:
27 |
28 | 1. 同步路由中的错误。如 `app.get('/', () => { throw new Error('kaboom') })`
29 | 2. `async` 路由中的错误。如 `app.get('/', async () => { throw new Error('kaboom') })`
30 |
31 | 上述错误都会被安全地捕捉,并移交给 Fastify 默认的错误处理函数,发送一个通用的 `500 Internal Server Error` 响应。
32 |
33 | 要自定义该行为,请见 [`setErrorHandler`](Server.md#seterrorhandler)。
34 |
35 | ### Fastify 生命周期钩子的错误,及自定义错误控制函数
36 |
37 | 在[钩子](Hooks.md#manage-errors-from-a-hook)的文档中提到:
38 | > 假如在钩子执行过程中发生错误,只需把它传递给 `done()`,Fastify 便会自动地关闭请求,并向用户发送合适的错误代码。
39 |
40 | 如果通过 `setErrorHandler` 自定义了一个错误函数,那么错误会被引导到那里,否则被引导到 Fastify 默认的错误函数中去。
41 |
42 | 自定义错误函数应该考虑以下几点:
43 |
44 | - 你可以调用 `reply.send(data)`,正如在[常规路由](Reply.md#senddata)中那样
45 | - object 会被序列化,并触发 `preSerialization` 钩子 (假如有定义的话)
46 | - string、buffer 及 stream 会被直接发送至客户端 (不会序列化),并附带上合适的 header。
47 |
48 | - 在错误函数里你可以抛出新的错误
49 | - 错误 (新的错误,或被重新抛出的错误参数) 会触发 `onError` 钩子,并被发送给用户
50 | - 在同一个钩子内,一个错误不会被触发两次。Fastify 会内在地监控错误的触发,以此避免在回复阶段无限循环地抛错 (在路由函数执行后)。
51 |
52 |
53 | ### Fastify 错误代码
54 |
55 |
56 | #### FST_ERR_BAD_URL
57 |
58 | 无效的 url。
59 |
60 |
61 | #### FST_ERR_CTP_ALREADY_PRESENT
62 |
63 | 该 content type 的解析器已经被注册。
64 |
65 |
66 | #### FST_ERR_CTP_BODY_TOO_LARGE
67 |
68 | 请求 body 大小超过限制。
69 |
70 | 可通过 Fastify 实例的 [`bodyLimit`](Server.md#bodyLimit) 属性改变大小限制。
71 |
72 |
73 | #### FST_ERR_CTP_EMPTY_TYPE
74 |
75 | content type 不能是一个空字符串。
76 |
77 |
78 | #### FST_ERR_CTP_INVALID_CONTENT_LENGTH
79 |
80 | 请求 body 大小与 Content-Length 不一致。
81 |
82 |
83 | #### FST_ERR_CTP_INVALID_HANDLER
84 |
85 | 该 content type 接收的处理函数无效。
86 |
87 |
88 | #### FST_ERR_CTP_INVALID_MEDIA_TYPE
89 |
90 | 收到的 media type 不支持 (例如,不存在合适的 `Content-Type` 解析器)。
91 |
92 |
93 | #### FST_ERR_CTP_INVALID_PARSE_TYPE
94 |
95 | 提供的待解析类型不支持。只支持 `string` 和 `buffer`。
96 |
97 |
98 | #### FST_ERR_CTP_INVALID_TYPE
99 |
100 | `Content-Type` 应为一个字符串。
101 |
102 |
103 | #### FST_ERR_DEC_ALREADY_PRESENT
104 |
105 | 已存在同名的装饰器。
106 |
107 |
108 | #### FST_ERR_DEC_MISSING_DEPENDENCY
109 |
110 | 缺失依赖导致装饰器无法注册。
111 |
112 |
113 | #### FST_ERR_HOOK_INVALID_HANDLER
114 |
115 | 钩子的回调必须为函数。
116 |
117 |
118 | #### FST_ERR_HOOK_INVALID_TYPE
119 |
120 | 钩子名称必须为字符串。
121 |
122 |
123 | #### FST_ERR_LOG_INVALID_DESTINATION
124 |
125 | 日志工具目标地址无效。仅接受 `'stream'` 或 `'file'` 作为目标地址。
126 |
127 |
128 | #### FST_ERR_PROMISE_NOT_FULLFILLED
129 |
130 | 状态码不为 204 时,Promise 的 payload 不能为 'undefined'。
131 |
132 |
133 | #### FST_ERR_REP_ALREADY_SENT
134 |
135 | 响应已发送。
136 |
137 |
138 | #### FST_ERR_REP_INVALID_PAYLOAD_TYPE
139 |
140 | 响应 payload 类型无效。只允许 `string` 或 `Buffer`。
141 |
142 |
143 | #### FST_ERR_SCH_ALREADY_PRESENT
144 |
145 | 同 `$id` 的 schema 已经存在。
146 |
147 |
148 | #### FST_ERR_SCH_MISSING_ID
149 |
150 | 提供的 schema 没有 `$id` 属性。
151 |
152 |
153 | #### FST_ERR_SCH_SERIALIZATION_BUILD
154 |
155 | 用于序列化响应的 JSON schema 不合法。
156 |
157 |
158 | #### FST_ERR_SCH_VALIDATION_BUILD
159 |
160 | 用于校验路由的 JSON schema 不合法。
161 |
162 |
163 | #### FST_ERR_SEND_INSIDE_ONERR
164 |
165 | 不能在 `onError` 钩子中调用 `send`。
166 |
167 |
168 | #### FST_ERR_SEND_UNDEFINED_ERR
169 |
170 | 发生了未定义的错误。
--------------------------------------------------------------------------------
/docs/Fluent-Schema.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## Fluent Schema
4 |
5 | 在[验证和序列化](Validation-and-Serialization.md)一文中,我们列明了使用 JSON schema 验证输入、优化输出时所有可用的参数。
6 |
7 | 现在,你可以使用 [`fluent-json-schema`](https://github.com/fastify/fluent-json-schema) 来更简单地设置 JSON schema,并且复用常量。
8 |
9 | ### 基本设置
10 |
11 | ```js
12 | const S = require('fluent-json-schema')
13 |
14 | // 你可以使用如下的一个对象,或查询数据库来获取数据
15 | const MY_KEYS = {
16 | KEY1: 'ONE',
17 | KEY2: 'TWO'
18 | }
19 |
20 | const bodyJsonSchema = S.object()
21 | .prop('someKey', S.string())
22 | .prop('someOtherKey', S.number())
23 | .prop('requiredKey', S.array().maxItems(3).items(S.integer()).required())
24 | .prop('nullableKey', S.mixed([S.TYPES.NUMBER, S.TYPES.NULL]))
25 | .prop('multipleTypesKey', S.mixed([S.TYPES.BOOLEAN, S.TYPES.NUMBER]))
26 | .prop('multipleRestrictedTypesKey', S.oneOf([S.string().maxLength(5), S.number().minimum(10)]))
27 | .prop('enumKey', S.enum(Object.values(MY_KEYS)))
28 | .prop('notTypeKey', S.not(S.array()))
29 |
30 | const queryStringJsonSchema = S.object()
31 | .prop('name', S.string())
32 | .prop('excitement', S.integer())
33 |
34 | const paramsJsonSchema = S.object()
35 | .prop('par1', S.string())
36 | .prop('par2', S.integer())
37 |
38 | const headersJsonSchema = S.object()
39 | .prop('x-foo', S.string().required())
40 |
41 | const schema = {
42 | body: bodyJsonSchema,
43 | querystring: queryStringJsonSchema, // (或) query: queryStringJsonSchema
44 | params: paramsJsonSchema,
45 | headers: headersJsonSchema
46 | }
47 |
48 | fastify.post('/the/url', { schema }, handler)
49 | ```
50 |
51 | ### 复用
52 |
53 | 使用 `fluent-json-schema`,你可以简单且程序化地处理 schema,并通过 `addSchema()` 来复用它们。
54 | 正如[验证和序列化](Validation-and-Serialization.md#adding-a-shared-schema)一文所述,有两种方法来引用 schema。
55 |
56 | 以下是一些例子:
57 |
58 | **`使用$ref`**:引用外部的 schema。
59 |
60 | ```js
61 | const addressSchema = S.object()
62 | .id('#address')
63 | .prop('line1').required()
64 | .prop('line2')
65 | .prop('country').required()
66 | .prop('city').required()
67 | .prop('zipcode').required()
68 |
69 | const commonSchemas = S.object()
70 | .id('https://fastify/demo')
71 | .definition('addressSchema', addressSchema)
72 | .definition('otherSchema', otherSchema) // 你可以任意添加需要的 schema
73 |
74 | fastify.addSchema(commonSchemas)
75 |
76 | const bodyJsonSchema = S.object()
77 | .prop('residence', S.ref('https://fastify/demo#address')).required()
78 | .prop('office', S.ref('https://fastify/demo#/definitions/addressSchema')).required()
79 |
80 | const schema = { body: bodyJsonSchema }
81 |
82 | fastify.post('/the/url', { schema }, handler)
83 | ```
84 |
85 |
86 | **`替换方式`**:在验证阶段之前,使用共用 schema 替换某些字段。
87 |
88 | ```js
89 | const sharedAddressSchema = {
90 | $id: 'sharedAddress',
91 | type: 'object',
92 | required: ['line1', 'country', 'city', 'zipcode'],
93 | properties: {
94 | line1: { type: 'string' },
95 | line2: { type: 'string' },
96 | country: { type: 'string' },
97 | city: { type: 'string' },
98 | zipcode: { type: 'string' }
99 | }
100 | }
101 | fastify.addSchema(sharedAddressSchema)
102 |
103 | const bodyJsonSchema = {
104 | type: 'object',
105 | properties: {
106 | vacation: 'sharedAddress#'
107 | }
108 | }
109 |
110 | const schema = { body: bodyJsonSchema }
111 |
112 | fastify.post('/the/url', { schema }, handler)
113 | ```
114 |
115 | 特别注意:你可以在 `fastify.addSchema` 方法里混用 `$ref` 和 `替换方式`。
--------------------------------------------------------------------------------
/docs/Getting-Started.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 起步
4 | Hello!感谢你来到 Fastify 的世界!
5 | 这篇文档将向你介绍 Fastify 框架及其特性,也包含了一些示例和指向其他文档的链接。
6 | 那,这就开始吧!
7 |
8 |
9 | ### 安装
10 | 使用 npm 安装:
11 | ```
12 | npm i fastify --save
13 | ```
14 | 使用 yarn 安装:
15 | ```
16 | yarn add fastify
17 | ```
18 |
19 |
20 | ### 第一个服务器
21 | 让我们开始编写第一个服务器吧:
22 | ```js
23 | // 加载框架并新建实例
24 |
25 | // ESM
26 | import Fastify from 'fastify'
27 | const fastify = Fastify({
28 | logger: true
29 | })
30 | // CommonJs
31 | const fastify = require('fastify')({
32 | logger: true
33 | })
34 |
35 | // 声明路由
36 | fastify.get('/', function (request, reply) {
37 | reply.send({ hello: 'world' })
38 | })
39 |
40 | // 启动服务!
41 | fastify.listen(3000, function (err, address) {
42 | if (err) {
43 | fastify.log.error(err)
44 | process.exit(1)
45 | }
46 | // 服务器监听地址:${address}
47 | })
48 | ```
49 |
50 | 更喜欢使用 `async/await`?Fastify 对其提供了开箱即用的支持。
51 | *(我们还建议使用 [make-promises-safe](https://github.com/mcollina/make-promises-safe) 来避免文件描述符 (file descriptor) 及内存的泄露)*
52 | ```js
53 | // ESM
54 | import Fastify from 'fastify'
55 | const fastify = Fastify({
56 | logger: true
57 | })
58 | // CommonJs
59 | const fastify = require('fastify')({
60 | logger: true
61 | })
62 |
63 | fastify.get('/', async (request, reply) => {
64 | return { hello: 'world' }
65 | })
66 |
67 | const start = async () => {
68 | try {
69 | await fastify.listen(3000)
70 | } catch (err) {
71 | fastify.log.error(err)
72 | process.exit(1)
73 | }
74 | }
75 | start()
76 | ```
77 |
78 | 如此简单,棒极了!
79 | 可是,一个复杂的应用需要比上例多得多的代码。当你从头开始构建一个应用时,会遇到一些典型的问题,如多个文件的操作、异步引导,以及代码结构的布置。
80 | 幸运的是,Fastify 提供了一个易于使用的平台,它能帮助你解决不限于上述的诸多问题!
81 |
82 | > ## 注
83 | > 本文档中的示例,默认情况下只监听本地 `127.0.0.1` 端口。要监听所有有效的 IPv4 端口,需要将代码修改为监听 `0.0.0.0`,如下所示:
84 | >
85 | > ```js
86 | > fastify.listen(3000, '0.0.0.0', function (err, address) {
87 | > if (err) {
88 | > fastify.log.error(err)
89 | > process.exit(1)
90 | > }
91 | > fastify.log.info(`server listening on ${address}`)
92 | > })
93 | > ```
94 | >
95 | > 类似地,`::1` 表示只允许本地的 IPv6 连接。而 `::` 表示允许所有 IPv6 地址的接入,当操作系统支持时,所有的 IPv4 地址也会被允许。
96 | >
97 | > 当使用 Docker 或其他容器部署时,使用 `0.0.0.0` 或 `::` 会是最简单的暴露应用的方式。
98 |
99 |
100 | ### 第一个插件
101 | 就如同在 JavaScript 中一切皆为对象,在 Fastify 中,一切都是插件 (plugin)。
102 | 在深入之前,先来看看插件系统是如何工作的吧!
103 | 让我们新建一个基本的服务器,但这回我们把路由 (route) 的声明从入口文件转移到一个外部文件。(参阅[路由声明](Routes.md))。
104 | ```js
105 | // ESM
106 | import Fastify from 'fastify'
107 | import firstRoute from './our-first-route'
108 | const fastify = Fastify({
109 | logger: true
110 | })
111 |
112 | fastify.register(firstRoute)
113 |
114 | fastify.listen(3000, function (err, address) {
115 | if (err) {
116 | fastify.log.error(err)
117 | process.exit(1)
118 | }
119 | // 服务器监听地址:${address}
120 | })
121 | ```
122 |
123 | ```js
124 | // CommonJs
125 | const fastify = require('fastify')({
126 | logger: true
127 | })
128 |
129 | fastify.register(require('./our-first-route'))
130 |
131 | fastify.listen(3000, function (err, address) {
132 | if (err) {
133 | fastify.log.error(err)
134 | process.exit(1)
135 | }
136 | // 服务器监听地址:${address}
137 | })
138 | ```
139 |
140 | ```js
141 | // our-first-route.js
142 |
143 | async function routes (fastify, options) {
144 | fastify.get('/', async (request, reply) => {
145 | return { hello: 'world' }
146 | })
147 | }
148 |
149 | module.exports = routes
150 | ```
151 | 这个例子调用了 `register` API,它是 Fastify 框架的核心,也是添加路由、插件等的唯一方法。
152 |
153 | 在本文的开头,我们提到 Fastify 提供了帮助应用异步引导的基础功能。为什么这一功能十分重要呢?
154 | 考虑一下,当存在数据库操作时,数据库连接需要在服务器接受外部请求之前完成。该如何解决这一问题呢?
155 | 典型的解决方案是使用复杂的回调函数或 Promise,但如此会造成框架的 API、其他库以及应用程序的代码混杂在一起。
156 | Fastify 则不走寻常路,它从本质上用最轻松的方式解决这一问题!
157 |
158 | 让我们重写上述示例,加入一个数据库连接。
159 |
160 | 首先,安装 `fastify-plugin` 和 `fastify-mongodb`:
161 |
162 | ```
163 | npm i --save fastify-plugin fastify-mongodb
164 | ```
165 |
166 | **server.js**
167 | ```js
168 | // ESM
169 | import Fastify from 'fastify'
170 | import dbConnector from './our-db-connector'
171 | import firstRoute from './our-first-route'
172 |
173 | const fastify = Fastify({
174 | logger: true
175 | })
176 | fastify.register(dbConnector)
177 | fastify.register(firstRoute)
178 |
179 | fastify.listen(3000, function (err, address) {
180 | if (err) {
181 | fastify.log.error(err)
182 | process.exit(1)
183 | }
184 | // 服务器监听地址:${address}
185 | })
186 | ```
187 |
188 | ```js
189 | // CommonJs
190 | const fastify = require('fastify')({
191 | logger: true
192 | })
193 |
194 | fastify.register(require('./our-db-connector'))
195 | fastify.register(require('./our-first-route'))
196 |
197 | fastify.listen(3000, function (err, address) {
198 | if (err) {
199 | fastify.log.error(err)
200 | process.exit(1)
201 | }
202 | // 服务器监听地址:${address}
203 | })
204 |
205 | ```
206 |
207 | **our-db-connector.js**
208 | ```js
209 | // ESM
210 | import fastifyPlugin from 'fastify-plugin'
211 | import fastifyMongo from 'fastify-mongodb'
212 |
213 | async function dbConnector (fastify, options) {
214 | fastify.register(fastifyMongo, {
215 | url: 'mongodb://localhost:27017/test_database'
216 | })
217 | }
218 |
219 | // 用 fastify-plugin 包装插件,以使插件中声明的装饰器、钩子函数暴露在根作用域里。
220 | module.exports = fastifyPlugin(dbConnector)
221 |
222 | ```
223 |
224 | ```js
225 | // CommonJs
226 | const fastifyPlugin = require('fastify-plugin')
227 |
228 | async function dbConnector (fastify, options) {
229 | fastify.register(require('fastify-mongodb'), {
230 | url: 'mongodb://localhost:27017/test_database'
231 | })
232 | }
233 | // 用 fastify-plugin 包装插件,以使插件中声明的装饰器、钩子函数暴露在根作用域里。
234 | module.exports = fastifyPlugin(dbConnector)
235 |
236 | ```
237 |
238 | **our-first-route.js**
239 | ```js
240 | async function routes (fastify, options) {
241 | const collection = fastify.mongo.db.collection('test_collection')
242 |
243 | fastify.get('/', async (request, reply) => {
244 | return { hello: 'world' }
245 | })
246 |
247 | fastify.get('/animals', async (request, reply) => {
248 | const result = await collection.find().toArray()
249 | if (result.length === 0) {
250 | throw new Error('No documents found')
251 | }
252 | return result
253 | })
254 |
255 | fastify.get('/animals/:animal', async (request, reply) => {
256 | const result = await collection.findOne({ animal: request.params.animal })
257 | if (!result) {
258 | throw new Error('Invalid value')
259 | }
260 | return result
261 | })
262 | }
263 |
264 | module.exports = routes
265 | ```
266 |
267 | 哇,真是快啊!
268 | 介绍了一些新概念后,让我们回顾一下迄今为止都做了些什么吧。
269 | 如你所见,我们可以使用 `register` 来注册数据库连接器或者路由。
270 | 这是 Fastify 最棒的特性之一了!它使得插件按声明的顺序来加载,唯有当前插件加载完毕后,才会加载下一个插件。如此,我们便可以在第一个插件中注册数据库连接器,并在第二个插件中使用它。*(参见 [这里](Plugins.md#handle-the-scope) 了解如何处理插件的作用域)*。
271 | 当调用函数 `fastify.listen()`、`fastify.inject()` 或 `fastify.ready()` 时,插件便开始加载了。
272 |
273 | MongoDB 的插件使用了 `decorate` API,以便在 Fastify 的命名空间下添加自定义对象,如此一来,你就可以在所有地方直接使用这些对象了。我们鼓励运用这一 API,因为它有助于提高代码复用率,减少重复的代码或逻辑。
274 |
275 | 更深入的内容,例如插件如何运作、如何新建,以及使用 Fastify 全部的 API 去处理复杂的异步引导的细节,请看[插件指南](Plugins-Guide.md)。
276 |
277 |
278 | ### 插件加载顺序
279 | 为了保证应用的行为一致且可预测,我们强烈建议你采用以下的顺序来组织代码:
280 | ```
281 | └── 来自 Fastify 生态的插件
282 | └── 你自己的插件
283 | └── 装饰器
284 | └── 钩子函数
285 | └── 你的服务应用
286 | ```
287 | 这确保了你总能访问当前作用域下声明的所有属性。
288 | 如前文所述,Fastify 提供了一个可靠的封装模型,它能帮助你的应用成为单一且独立的服务。假如你要为某些路由单独地注册插件,只需复写上述的结构就足够了。
289 | ```
290 | └── 来自 Fastify 生态的插件
291 | └── 你自己的插件
292 | └── 装饰器
293 | └── 钩子函数
294 | └── 你的服务应用
295 | │
296 | └── 服务 A
297 | │ └── 来自 Fastify 生态的插件
298 | │ └── 你自己的插件
299 | │ └── 装饰器
300 | │ └── 钩子函数
301 | │ └── 你的服务应用
302 | │
303 | └── 服务 B
304 | │ └── 来自 Fastify 生态的插件
305 | │ └── 你自己的插件
306 | │ └── 装饰器
307 | │ └── 钩子函数
308 | │ └── 你的服务应用
309 | ```
310 |
311 |
312 | ### 验证数据
313 | 数据的验证在我们的框架中是极为重要的一环,也是核心的概念。
314 | Fastify 使用 [JSON Schema](https://json-schema.org/) 验证来访的请求。(也支持宽松的 JTD schema,但首先得禁用 `jsonShorthand`)。
315 |
316 | 让我们来看一个验证路由的例子:
317 | ```js
318 | const opts = {
319 | schema: {
320 | body: {
321 | type: 'object',
322 | properties: {
323 | someKey: { type: 'string' },
324 | someOtherKey: { type: 'number' }
325 | }
326 | }
327 | }
328 | }
329 |
330 | fastify.post('/', opts, async (request, reply) => {
331 | return { hello: 'world' }
332 | })
333 | ```
334 | 这个例子展示了如何向路由传递配置选项。选项中包含了一个名为 `schema` 的对象,它便是我们验证路由所用的模式 (schema)。借由 schema,我们可以验证 `body`、`querystring`、`params` 以及 `header`。
335 | 请参阅[验证与序列化](Validation-and-Serialization.md)获取更多信息。
336 |
337 |
338 | ### 序列化数据
339 | Fastify 对 JSON 提供了优异的支持,极大地优化了解析 JSON body 与序列化 JSON 输出的过程。
340 | 在 schema 的选项中设置 `response` 的值,能够加快 JSON 的序列化 (没错,这很慢!),就像这样:
341 | ```js
342 | const opts = {
343 | schema: {
344 | response: {
345 | 200: {
346 | type: 'object',
347 | properties: {
348 | hello: { type: 'string' }
349 | }
350 | }
351 | }
352 | }
353 | }
354 |
355 | fastify.get('/', opts, async (request, reply) => {
356 | return { hello: 'world' }
357 | })
358 | ```
359 | 一旦指明了 schema,序列化的速度就能达到原先的 2-3 倍。这么做同时也保护了潜在的敏感数据不被泄露,因为 Fastify 仅对 schema 里出现的数据进行序列化。
360 | 请参阅 [验证与序列化](Validation-and-Serialization.md)获取更多信息。
361 |
362 |
363 | ### 扩展服务器
364 | Fastify 生来十分精简,也具有高可扩展性。我们相信,一个小巧的框架足以实现一个优秀的应用。
365 | 换句话说,Fastify 并非一个面面俱到的框架,它依赖于自己惊人的[生态系统](https://github.com/fastify/fastify/blob/main/docs/Ecosystem.md)!
366 |
367 |
368 | ### 测试服务器
369 | Fastify 并没有提供测试框架,但是我们推荐你在测试中使用 Fastify 的特性及结构。
370 | 更多内容请看[测试](Testing.md)!
371 |
372 |
373 | ### 从命令行启动服务器
374 | 感谢 [fastify-cli](https://github.com/fastify/fastify-cli),它让 Fastify 集成到了命令行之中。
375 |
376 | 首先,你得安装 `fastify-cli`:
377 |
378 | ```
379 | npm i fastify-cli
380 | ```
381 |
382 | 你还可以加入 `-g` 选项来全局安装它。
383 |
384 | 接下来,在 `package.json` 中添加如下行:
385 | ```json
386 | {
387 | "scripts": {
388 | "start": "fastify start server.js"
389 | }
390 | }
391 | ```
392 |
393 | 然后,创建你的服务器文件:
394 | ```js
395 | // server.js
396 | 'use strict'
397 |
398 | module.exports = async function (fastify, opts) {
399 | fastify.get('/', async (request, reply) => {
400 | return { hello: 'world' }
401 | })
402 | }
403 | ```
404 |
405 | 最后,启动你的服务器:
406 | ```bash
407 | npm start
408 | ```
409 |
410 |
411 | ### 幻灯片与视频 (英文资源)
412 | - 幻灯片
413 | - [为你的 HTTP 服务器提速](https://mcollina.github.io/take-your-http-server-to-ludicrous-speed) by [@mcollina](https://github.com/mcollina)
414 | - [如果我告诉你 HTTP 可以更快](https://delvedor.github.io/What-if-I-told-you-that-HTTP-can-be-fast) by [@delvedor](https://github.com/delvedor)
415 |
416 | - 视频
417 | - [为你的 HTTP 服务器提速](https://www.youtube.com/watch?v=5z46jJZNe8k) by [@mcollina](https://github.com/mcollina)
418 | - [如果我告诉你 HTTP 可以更快](https://www.webexpo.net/prague2017/talk/what-if-i-told-you-that-http-can-be-fast/) by [@delvedor](https://github.com/delvedor)
419 |
--------------------------------------------------------------------------------
/docs/HTTP2.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## HTTP2
4 |
5 | _Fastify_ 提供了从 Node 8.8.0 开始的对 HTTP2 **实验性支持**,_Fastify_ 支持 HTTPS 和普通文本的 HTTP2 支持。需要注意的是,Node 8.8.1 以上的版本才支持 HTTP2。
6 |
7 | 当前没有任何 HTTP2 相关的 APIs 是可用的,但 Node `req` 和 `res` 可以通过 `Request` 和 `Reply` 接口访问。欢迎相关的 PR。
8 |
9 | ### 安全 (HTTPS)
10 |
11 | 所有的现代浏览器都__只能通过安全的连接__ 支持 HTTP2:
12 |
13 | ```js
14 | 'use strict'
15 |
16 | const fs = require('fs')
17 | const path = require('path')
18 | const fastify = require('fastify')({
19 | http2: true,
20 | https: {
21 | key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
22 | cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
23 | }
24 | })
25 |
26 | fastify.get('/', function (request, reply) {
27 | reply.code(200).send({ hello: 'world' })
28 | })
29 |
30 | fastify.listen(3000)
31 | ```
32 |
33 | ALPN 协商允许在同一个 socket 上支持 HTTPS 和 HTTP/2。
34 | Node 核心 `req` 和 `res` 对象可以是 [HTTP/1](https://nodejs.org/api/http.html)
35 | 或者 [HTTP/2](https://nodejs.org/api/http2.html)。
36 | _Fastify_ 自带支持开箱即用:
37 |
38 | ```js
39 | 'use strict'
40 |
41 | const fs = require('fs')
42 | const path = require('path')
43 | const fastify = require('fastify')({
44 | http2: true,
45 | https: {
46 | allowHTTP1: true, // 向后支持 HTTP1
47 | key: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.key')),
48 | cert: fs.readFileSync(path.join(__dirname, '..', 'https', 'fastify.cert'))
49 | }
50 | })
51 |
52 | // 该路由从 HTTPS 与 HTTP2 均可访问
53 | fastify.get('/', function (request, reply) {
54 | reply.code(200).send({ hello: 'world' })
55 | })
56 |
57 | fastify.listen(3000)
58 | ```
59 |
60 | 你可以像这样测试你的新服务器:
61 |
62 | ```
63 | $ npx h2url https://localhost:3000
64 | ```
65 |
66 | ### 纯文本或者不安全
67 |
68 | 如果你搭建微服务,你可以纯文本连接 HTTP2,但是浏览器不支持这样做。
69 |
70 | ```js
71 | 'use strict'
72 |
73 | const fastify = require('fastify')({
74 | http2: true
75 | })
76 |
77 | fastify.get('/', function (request, reply) {
78 | reply.code(200).send({ hello: 'world' })
79 | })
80 |
81 | fastify.listen(3000)
82 | ```
83 |
84 | 你可以像这样测试你的新服务器:
85 |
86 | ```
87 | $ npx h2url http://localhost:3000
88 | ```
89 |
90 |
--------------------------------------------------------------------------------
/docs/Hooks.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 钩子方法
4 |
5 | 钩子 (hooks) 让你能够监听应用或请求/响应生命周期之上的特定事件。使用 `fastify.addHook` 可以注册钩子。你必须在事件被触发之前注册相应的钩子,否则,事件将得不到处理。
6 |
7 | 通过钩子方法,你可以与 Fastify 的生命周期直接进行交互。有用于请求/响应的钩子,也有应用级钩子:
8 |
9 | - [请求/响应钩子](#requestreply-hooks)
10 | - [onRequest](#onrequest)
11 | - [preParsing](#preparsing)
12 | - [preValidation](#prevalidation)
13 | - [preHandler](#prehandler)
14 | - [preSerialization](#preserialization)
15 | - [onError](#onerror)
16 | - [onSend](#onsend)
17 | - [onResponse](#onresponse)
18 | - [onTimeout](#ontimeout)
19 | - [在钩子中管理错误](#manage-errors-from-a-hook)
20 | - [在钩子中响应请求](#respond-to-a-request-from-a-hook)
21 | - [应用钩子](#application-hooks)
22 | - [onReady](#onready)
23 | - [onClose](#onclose)
24 | - [onRoute](#onroute)
25 | - [onRegister](#onregister)
26 | - [作用域](#scope)
27 | - [路由层钩子](#route-level-hooks)
28 |
29 | **注意**:使用 `async`/`await` 或返回一个 `Promise` 时,`done` 回调不可用。在这种情况下,仍然使用 `done` 可能会导致难以预料的行为,例如,处理函数的重复调用。
30 |
31 | ## 请求/响应钩子
32 |
33 | [Request](Request.md) 与 [Reply](Reply.md) 是 Fastify 核心的对象。
34 | `done` 是调用[生命周期](Lifecycle.md)下一阶段的函数。
35 |
36 | [生命周期](Lifecycle.md)一文清晰地展示了各个钩子执行的位置。
37 | 钩子可被封装,因此可以运用在特定的路由上。更多信息请看[作用域](#scope)一节。
38 |
39 | 在请求/响应中,有八个可用的钩子 *(按执行顺序排序)*:
40 |
41 | ### onRequest
42 | ```js
43 | fastify.addHook('onRequest', (request, reply, done) => {
44 | // 其他代码
45 | done()
46 | })
47 | ```
48 | 或使用 `async/await`:
49 | ```js
50 | fastify.addHook('onRequest', async (request, reply) => {
51 | // 其他代码
52 | await asyncMethod()
53 | })
54 | ```
55 |
56 | **注意**:在 [onRequest](#onrequest) 钩子中,`request.body` 的值总是 `null`,这是因为 body 的解析发生在 [preValidation](#prevalidation) 钩子之前。
57 |
58 | ### preParsing
59 |
60 | `preParsing` 钩子让你能在解析请求之前转换它们。它的参数除了和其他钩子一样的请求与响应对象外,还多了一个当前请求 payload 的 stream。
61 |
62 | 需要通过 `return` 或回调函数返回值的话,必须返回一个 stream。
63 |
64 | 例如,你可以解压请求的 body:
65 |
66 | ```js
67 | fastify.addHook('preParsing', (request, reply, payload, done) => {
68 | // 其他代码
69 | done(null, newPayload)
70 | })
71 | ```
72 | 或使用 `async/await`:
73 | ```js
74 | fastify.addHook('preParsing', async (request, reply, payload) => {
75 | // 其他代码
76 | await asyncMethod()
77 | return newPayload
78 | })
79 | ```
80 |
81 | **注意**:在 [preParsing](#preparsing) 钩子中,`request.body` 的值总是 `null`,这是因为 body 的解析发生在 [preValidation](#prevalidation) 钩子之前。
82 |
83 | **注意**:你应当给返回的 stream 添加 `receivedEncodedLength` 属性。这是为了通过比对请求头的 `Content-Length`,来精确匹配请求的 payload。理想情况下,每收到一块数据都应该更新该属性。
84 |
85 | **注意**:早先的写法 `function(request, reply, done)` 与 `function(request, reply)` 仍被支持,但不推荐使用。
86 |
87 | ### preValidation
88 |
89 | 使用 `preValidation` 钩子时,你可以在校验前修改 payload。示例如下:
90 |
91 | ```js
92 | fastify.addHook('preValidation', (request, reply, done) => {
93 | req.body = { ...req.body, importantKey: 'randomString' }
94 | done()
95 | })
96 | ```
97 | 或使用 `async/await`:
98 | ```js
99 | fastify.addHook('preValidation', async (request, reply) => {
100 | const importantKey = await generateRandomString()
101 | req.body = { ...req.body, importantKey }
102 | })
103 | ```
104 |
105 | ### preHandler
106 | ```js
107 | fastify.addHook('preHandler', (request, reply, done) => {
108 | // 其他代码
109 | done()
110 | })
111 | ```
112 | 或使用 `async/await`:
113 | ```js
114 | fastify.addHook('preHandler', async (request, reply) => {
115 | // 其他代码
116 | await asyncMethod()
117 | })
118 | ```
119 | ### preSerialization
120 |
121 | `preSerialization` 钩子让你可以在 payload 被序列化之前改动 (或替换) 它。举个例子:
122 |
123 | ```js
124 | fastify.addHook('preSerialization', (request, reply, payload, done) => {
125 | const err = null
126 | const newPayload = { wrapped: payload }
127 | done(err, newPayload)
128 | })
129 | ```
130 | 或使用 `async/await`:
131 | ```js
132 | fastify.addHook('preSerialization', async (request, reply, payload) => {
133 | return { wrapped: payload }
134 | })
135 | ```
136 |
137 | 注:payload 为 `string`、`Buffer`、`stream` 或 `null` 时,该钩子不会被调用。
138 |
139 | ### onError
140 | ```js
141 | fastify.addHook('onError', (request, reply, error, done) => {
142 | // 其他代码
143 | done()
144 | })
145 | ```
146 | 或使用 `async/await`:
147 | ```js
148 | fastify.addHook('onError', async (request, reply, error) => {
149 | // 当自定义错误日志时有用处
150 | // 你不应该使用这个钩子去更新错误
151 | })
152 | ```
153 | `onError` 钩子可用于自定义错误日志,或当发生错误时添加特定的 header。
154 | 该钩子并不是为了变更错误而设计的,且调用 `reply.send` 会抛出一个异常。
155 | 它只会在 `customErrorHandler` 向用户发送错误之后被执行 (要注意的是,默认的 `customErrorHandler` 总是会发送错误)。
156 | **注意**:与其他钩子不同,`onError` 不支持向 `done` 函数传递错误。
157 |
158 | ### onSend
159 | 使用 `onSend` 钩子可以改变 payload。例如:
160 |
161 | ```js
162 | fastify.addHook('onSend', (request, reply, payload, done) => {
163 | const err = null;
164 | const newPayload = payload.replace('some-text', 'some-new-text')
165 | done(err, newPayload)
166 | })
167 | ```
168 | 或使用 `async/await`:
169 | ```js
170 | fastify.addHook('onSend', async (request, reply, payload) => {
171 | const newPayload = payload.replace('some-text', 'some-new-text')
172 | return newPayload
173 | })
174 | ```
175 |
176 | 你也可以通过将 payload 置为 `null`,发送一个空消息主体的响应:
177 |
178 | ```js
179 | fastify.addHook('onSend', (request, reply, payload, done) => {
180 | reply.code(304)
181 | const newPayload = null
182 | done(null, newPayload)
183 | })
184 | ```
185 |
186 | > 将 payload 设为空字符串 `''` 也可以发送空的消息主体。但要小心的是,这么做会造成 `Content-Length` header 的值为 `0`。而 payload 为 `null` 则不会设置 `Content-Length` header。
187 |
188 | 注:你只能将 payload 修改为 `string`、`Buffer`、`stream` 或 `null`。
189 |
190 |
191 | ### onResponse
192 | ```js
193 |
194 | fastify.addHook('onResponse', (request, reply, done) => {
195 | // 其他代码
196 | done()
197 | })
198 | ```
199 | 或使用 `async/await`:
200 | ```js
201 | fastify.addHook('onResponse', async (request, reply) => {
202 | // 其他代码
203 | await asyncMethod()
204 | })
205 | ```
206 |
207 | `onResponse` 钩子在响应发出后被执行,因此在该钩子中你无法再向客户端发送数据了。但是你可以在此向外部服务发送数据,比如收集数据。
208 |
209 | ### onTimeout
210 |
211 | ```js
212 | fastify.addHook('onTimeout', (request, reply, done) => {
213 | // 其他代码
214 | done()
215 | })
216 | ```
217 | Or `async/await`:
218 | ```js
219 | fastify.addHook('onTimeout', async (request, reply) => {
220 | // 其他代码
221 | await asyncMethod()
222 | })
223 | ```
224 | `onTimeout` 用于监测请求超时,需要在 Fastify 实例上设置 `connectionTimeout` 属性。当请求超时,socket 挂起 (hang up) 时,该钩子执行。因此,在这个钩子里不能再向客户端发送数据了。
225 |
226 | ### 在钩子中管理错误
227 | 在钩子的执行过程中如果发生了错误,只需将错误传递给 `done()`,Fastify 就会自动关闭请求,并发送一个相应的错误码给用户。
228 |
229 | ```js
230 | fastify.addHook('onRequest', (request, reply, done) => {
231 | done(new Error('Some error'))
232 | })
233 | ```
234 |
235 | 如果你想自定义发送给用户的错误码,使用 `reply.code()` 即可:
236 | ```js
237 | fastify.addHook('preHandler', (request, reply, done) => {
238 | reply.code(400)
239 | done(new Error('Some error'))
240 | })
241 | ```
242 | *错误最终会在 [`Reply`](Reply.md#errors) 中得到处理。*
243 |
244 | 或者在 `async/await` 函数中抛出错误:
245 | ```js
246 | fastify.addHook('onResponse', async (request, reply) => {
247 | throw new Error('Some error')
248 | })
249 | ```
250 |
251 | ### 在钩子中响应请求
252 |
253 | 需要的话,你可以在路由函数执行前响应一个请求,例如进行身份验证。在钩子中响应暗示着钩子的调用链被 __终止__,剩余的钩子将不会执行。假如钩子使用回调的方式,意即不是 `async` 函数,也没有返回 `Promise`,那么只需要调用 `reply.send()`,并且避免触发回调便可。假如钩子是 `async` 函数,那么 `reply.send()` __必须__ 发生在函数返回或 promise resolve 之前,否则请求将会继续下去。当 `reply.send()` 在 promise 调用链之外被调用时,需要 `return reply`,不然请求将被执行两次。
254 |
255 | __不应当混用回调与 `async`/`Promise`__,否则钩子的调用链会被执行两次。
256 |
257 | 如果你在 `onRequest` 或 `preHandler` 中发出响应,请使用 `reply.send`。
258 |
259 | ```js
260 | fastify.addHook('onRequest', (request, reply, done) => {
261 | reply.send('Early response')
262 | })
263 |
264 | // 也可使用 async 函数
265 | fastify.addHook('preHandler', async (request, reply) => {
266 | await something()
267 | reply.send({ hello: 'world' })
268 | return reply // 在这里是可选的,但这是好的实践
269 | })
270 | ```
271 |
272 | 如果你想要使用流 (stream) 来响应请求,你应该避免使用 `async` 函数。必须使用 `async` 函数的话,请参考 [test/hooks-async.js](https://github.com/fastify/fastify/blob/94ea67ef2d8dce8a955d510cd9081aabd036fa85/test/hooks-async.js#L269-L275) 中的示例来编写代码。
273 |
274 | ```js
275 | fastify.addHook('onRequest', (request, reply, done) => {
276 | const stream = fs.createReadStream('some-file', 'utf8')
277 | reply.send(stream)
278 | })
279 | ```
280 |
281 | 如果发出响应但没有 `await` 关键字,请确保总是 `return reply`:
282 |
283 | ```js
284 | fastify.addHook('preHandler', async (request, reply) => {
285 | setImmediate(() => { reply.send('hello') })
286 | // 让处理函数等待 promise 链之外发出的响应
287 | return reply
288 | })
289 | fastify.addHook('preHandler', async (request, reply) => {
290 | // fastify-static 插件异步地发送文件,因此需要 return reply
291 | reply.sendFile('myfile')
292 | return reply
293 | })
294 | ```
295 |
296 | ## 应用钩子
297 |
298 | 你也可以在应用的生命周期里使用钩子方法。要格外注意的是,这些钩子并未被完全封装。钩子中的 `this` 得到了封装,但处理函数可以响应封装界线外的事件。
299 |
300 | - [onReady](#onready)
301 | - [onClose](#onclose)
302 | - [onRoute](#onroute)
303 | - [onRegister](#onregister)
304 |
305 | ### onReady
306 | 在服务器开始监听请求之前,或调用 `.ready()` 方法时触发。在此你无法更改路由,或添加新的钩子。注册的 `onReady` 钩子函数串行执行,只有全部执行完毕时,服务器才会开始监听请求。钩子接受一个回调函数作为参数:`done`,在钩子函数完成后调用。钩子的 `this` 为 Fastify 实例。
307 |
308 | ```js
309 | // 回调写法
310 | fastify.addHook('onReady', function (done) {
311 | // 其他代码
312 | const err = null;
313 | done(err)
314 | })
315 |
316 | // 或 async/await
317 | fastify.addHook('onReady', async function () {
318 | // 异步代码
319 | await loadCacheFromDatabase()
320 | })
321 | ```
322 |
323 |
324 | ### onClose
325 | 使用 `fastify.close()` 停止服务器时被触发。当[插件](Plugins.md)需要一个 "shutdown" 事件时有用,例如关闭一个数据库连接。
326 | 该钩子的第一个参数是 Fastify 实例,第二个为 `done` 回调函数。
327 | ```js
328 | fastify.addHook('onClose', (instance, done) => {
329 | // 其他代码
330 | done()
331 | })
332 | ```
333 |
334 |
335 | ### onRoute
336 | 当注册一个新的路由时被触发。它的监听函数拥有一个唯一的参数:`routeOptions` 对象。该函数是同步的,其本身并不接受回调作为参数。
337 | ```js
338 | fastify.addHook('onRoute', (routeOptions) => {
339 | // 其他代码
340 | routeOptions.method
341 | routeOptions.schema
342 | routeOptions.url // 路由的完整 URL,包括前缀
343 | routeOptions.path // `url` 的别名
344 | routeOptions.routePath // 无前缀的 URL
345 | routeOptions.bodyLimit
346 | routeOptions.logLevel
347 | routeOptions.logSerializers
348 | routeOptions.prefix
349 | })
350 | ```
351 |
352 | 如果在编写插件时,需要自定义程序的路由,比如修改选项或添加新的路由层钩子,你可以在这里添加。
353 |
354 | ```js
355 | fastify.addHook('onRoute', (routeOptions) => {
356 | function onPreSerialization(request, reply, payload, done) {
357 | // 其他代码
358 | done(null, payload)
359 | }
360 |
361 | // preSerialization 可以是数组或 undefined
362 | routeOptions.preSerialization = [...(routeOptions.preSerialization || []), onPreSerialization]
363 | })
364 | ```
365 |
366 |
367 | ### onRegister
368 | 当注册一个新的插件,或创建了新的封装好的上下文后被触发。该钩子在注册的代码**之前**被执行。
369 | 当你的插件需要知晓上下文何时创建完毕,并操作它们时,可以使用这一钩子。
370 | **注意**:被 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 所封装的插件不会触发该钩子。
371 | ```js
372 | fastify.decorate('data', [])
373 |
374 | fastify.register(async (instance, opts) => {
375 | instance.data.push('hello')
376 | console.log(instance.data) // ['hello']
377 |
378 | instance.register(async (instance, opts) => {
379 | instance.data.push('world')
380 | console.log(instance.data) // ['hello', 'world']
381 | }), { prefix: '/hola' })
382 | }), { prefix: '/ciao' })
383 |
384 | fastify.register(async (instance, opts) => {
385 | console.log(instance.data) // []
386 | }), { prefix: '/hello' })
387 |
388 | fastify.addHook('onRegister', (instance, opts) => {
389 | // 从旧数组浅拷贝,
390 | // 生成一个新数组,
391 | // 使用户获得一个
392 | // 封装好的 `data` 的实例
393 | instance.data = instance.data.slice()
394 |
395 | // 新注册实例的选项
396 | console.log(opts.prefix)
397 | })
398 | ```
399 |
400 |
401 | ## 作用域
402 | 除了[应用钩子](#application-hooks),所有的钩子都是封装好的。这意味着你可以通过 `register` 来决定在何处运行它们,正如[插件指南](Plugins-Guide.md)所述。如果你传递一个函数,那么该函数会获得 Fastify 的上下文,如此你便能使用 Fastify 的 API 了。
403 |
404 | ```js
405 | fastify.addHook('onRequest', function (request, reply, done) {
406 | const self = this // Fastify 上下文
407 | done()
408 | })
409 | ```
410 |
411 | 要注意的是,每个钩子内的 Fastify 上下文都和注册路由时的插件一样,举例如下:
412 |
413 | ```js
414 | fastify.addHook('onRequest', async function (req, reply) {
415 | if (req.raw.url === '/nested') {
416 | assert.strictEqual(this.foo, 'bar')
417 | } else {
418 | assert.strictEqual(this.foo, undefined)
419 | }
420 | })
421 |
422 | fastify.get('/', async function (req, reply) {
423 | assert.strictEqual(this.foo, undefined)
424 | return { hello: 'world' }
425 | })
426 |
427 | fastify.register(async function plugin (fastify, opts) {
428 | fastify.decorate('foo', 'bar')
429 |
430 | fastify.get('/nested', async function (req, reply) {
431 | assert.strictEqual(this.foo, 'bar')
432 | return { hello: 'world' }
433 | })
434 | })
435 | ```
436 |
437 | 提醒:使用[箭头函数](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)的话,`this` 将不会是 Fastify,而是当前的作用域。
438 |
439 |
440 |
441 | ## 路由层钩子
442 | 你可以为**单个**路由声明一个或多个自定义的生命周期钩子 ([onRequest](#onrequest)、[onResponse](#onresponse)、[preParsing](#preparsing)、[preValidation](#prevalidation)、[preHandler](#prehandler)、[preSerialization](#preserialization)、[onSend](#onsend)、[onTimeout](#ontimeout) 与 [onError](#onerror))。
443 | 如果你这么做,这些钩子总是会作为同一类钩子中的最后一个被执行。
444 | 当你需要进行认证时,这会很有用,而 [preParsing](#preparsing) 与 [preValidation](#prevalidation) 钩子正是为此而生。
445 | 你也可以通过数组定义多个路由层钩子。
446 |
447 | ```js
448 | fastify.addHook('onRequest', (request, reply, done) => {
449 | // 你的代码
450 | done()
451 | })
452 |
453 | fastify.addHook('onResponse', (request, reply, done) => {
454 | // 你的代码
455 | done()
456 | })
457 |
458 | fastify.addHook('preParsing', (request, reply, done) => {
459 | // 你的代码
460 | done()
461 | })
462 |
463 | fastify.addHook('preValidation', (request, reply, done) => {
464 | // 你的代码
465 | done()
466 | })
467 |
468 | fastify.addHook('preHandler', (request, reply, done) => {
469 | // 你的代码
470 | done()
471 | })
472 |
473 | fastify.addHook('preSerialization', (request, reply, payload, done) => {
474 | // 你的代码
475 | done(null, payload)
476 | })
477 |
478 | fastify.addHook('onSend', (request, reply, payload, done) => {
479 | // 你的代码
480 | done(null, payload)
481 | })
482 |
483 | fastify.addHook('onTimeout', (request, reply, done) => {
484 | // 你的代码
485 | done()
486 | })
487 |
488 | fastify.addHook('onError', (request, reply, error, done) => {
489 | // 你的代码
490 | done()
491 | })
492 |
493 | fastify.route({
494 | method: 'GET',
495 | url: '/',
496 | schema: { ... },
497 | onRequest: function (request, reply, done) {
498 | // 该钩子总是在共享的 `onRequest` 钩子后被执行
499 | done()
500 | },
501 | onResponse: function (request, reply, done) {
502 | // 该钩子总是在共享的 `onResponse` 钩子后被执行
503 | done()
504 | },
505 | preParsing: function (request, reply, done) {
506 | // 该钩子总是在共享的 `preParsing` 钩子后被执行
507 | done()
508 | },
509 | preValidation: function (request, reply, done) {
510 | // 该钩子总是在共享的 `preValidation` 钩子后被执行
511 | done()
512 | },
513 | preHandler: function (request, reply, done) {
514 | // 该钩子总是在共享的 `preHandler` 钩子后被执行
515 | done()
516 | },
517 | // // 使用数组的例子。所有钩子都支持这一语法。
518 | //
519 | // preHandler: [function (request, reply, done) {
520 | // // 该钩子总是在共享的 `preHandler` 钩子后被执行
521 | // done()
522 | // }],
523 | preSerialization: (request, reply, payload, done) => {
524 | // 该钩子总是在共享的 `preSerialization` 钩子后被执行
525 | done(null, payload)
526 | },
527 | onSend: (request, reply, payload, done) => {
528 | // 该钩子总是在共享的 `onSend` 钩子后被执行
529 | done(null, payload)
530 | },
531 | onTimeout: (request, reply, done) => {
532 | // 该钩子总是在共享的 `onTimeout` 钩子后被执行
533 | done()
534 | },
535 | onError: (request, reply, error, done) => {
536 | // 该钩子总是在共享的 `onError` 钩子后被执行
537 | done()
538 | },
539 | handler: function (request, reply) {
540 | reply.send({ hello: 'world' })
541 | }
542 | })
543 | ```
544 |
545 | **注**:两个选项都接受一个函数数组作为参数。
546 |
547 | ## 诊断通道钩子
548 |
549 | > **注:** `诊断通道` (diagnostics_channel) 是当前 Node.js 的试验特性,
550 | > 因此,其 API 即便在补丁版本中也可能会发生变动。
551 | > 对于 Fastify 支持的 Node.js 版本,不兼容 `诊断通道` 的,
552 | > 将会使用 [polyfill](https://www.npmjs.com/package/diagnostics_channel)。
553 | > 而 polyfill 都不支持的版本将无法使用该特性。
554 |
555 | 当前版本在初始化时,会有一个[`诊断通道`](https://nodejs.org/api/diagnostics_channel.html)发布 `'fastify.initialization'` 事件。此时,Fastify 的实例将会作为回调函数参数的一个属性,该实例可以添加钩子、插件、路由及其他任意内容。
556 |
557 | 举例来说,某个监控工具可以如下使用(当然这是一个简化的例子)。在典型的“探测工具优先加载 (require instrumentation
558 | tools first)”风格下,这段代码会在被监控的应用初始化时加载。
559 |
560 | ```js
561 | const tracer = /* 某个监控工具 */
562 | const dc = require('diagnostics_channel')
563 | const channel = dc.channel('fastify.initialization')
564 | const spans = new WeakMap()
565 |
566 | channel.subscribe(function ({ fastify }) {
567 | fastify.addHook('onRequest', (request, reply, done) => {
568 | const span = tracer.startSpan('fastify.request')
569 | spans.set(request, span)
570 | done()
571 | })
572 |
573 | fastify.addHook('onResponse', (request, reply, done) => {
574 | const span = spans.get(request)
575 | span.finish()
576 | done()
577 | })
578 | })
579 | ```
--------------------------------------------------------------------------------
/docs/LTS.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 |
4 |
5 | ## 长期支持计划
6 |
7 | Fastify 长期支持计划 (LTS) 以本文档为准:
8 |
9 | 1. 主要版本发布,[语义化版本][semver] X.Y.Z 发布版本中的 "X" 发布,至少有6个月的支持。特定版本的发布日期可以从[https://github.com/fastify/fastify/releases](https://github.com/fastify/fastify/releases)查到。
10 |
11 | 1. 主要版本将一直获得安全更新,直到下个主要版本发布后的6个月后。在这之后我们依然会发布安全补丁,只要社区有提供,且不会破坏其他约束,例如,支持的 Node.js 最低版本。
12 |
13 | 1. 主要版本会针对其长期支持期内的所有[长期支持的 Node.js 版本](https://github.com/nodejs/Release)进行测试验证。这意味着,只有每行中最新的 Node.js 版本会得到支持。
14 |
15 | "月" 意思为连续的30天。
16 |
17 | > ## 安全版本与语义化 Security Releases and Semver
18 | >
19 | > 由于为主要版本提供长期支持十分重要,
20 | > 我们有时需要在 _次要版本_ 上发布重大的改动。
21 | > 这些变更 _总是_ 会记录在[发布记录](https://github.com/fastify/fastify/releases)里。
22 | >
23 | > 要避免自动升级到重大的安全更新版本,
24 | > 你可以使用波浪号 (`~`) 来标识版本范围。
25 | > 例如,将依赖标识为 `"fastify": "~3.15.x"`,
26 | > 可以为 3.15 更新补丁,也避免了自动升级到 3.16。
27 | > 这么做会使你的应用变得脆弱,因此请谨慎使用。
28 |
29 | [semver]: https://semver.org/
30 |
31 |
32 |
33 | ### 计划
34 |
35 | | 版本 | 发布日期 | 长期支持结束 | Node.js 版本 |
36 | | :------ | :----------- | :-------------- | :------------------- |
37 | | 1.0.0 | 2018-03-06 | 2019-09-01 | 6, 8, 9, 10, 11 |
38 | | 2.0.0 | 2019-02-25 | 2021-01-31 | 6, 8, 10, 12, 14 |
39 | | 3.0.0 | 2020-07-07 | 待定 | 10, 12, 14, 16 |
40 |
41 |
42 |
43 | ### 经过 CI (持续集成) 测试的操作系统
44 |
45 | Fastify 使用 GitHub Actions 来进行 CI 测试,请参阅 [GitHub 相关文档](https://docs.github.com/cn/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources)来获取下表 YAML 工作流标签所对应的最新虚拟机环境。
46 |
47 | | 系统 | YAML 工作流标签 | 包管理器 | Node.js |
48 | |---------|------------------------|---------------------------|--------------|
49 | | Linux | `ubuntu-latest` | npm | 10,12,14,16 |
50 | | Linux | `ubuntu-18.04` | yarn,pnpm | 10,12 |
51 | | Windows | `windows-latest` | npm | 10,12,14,16 |
52 | | MacOS | `macos-latest` | npm | 10,12,14,16 |
53 |
54 | 使用 [yarn](https://yarnpkg.com/) 命令需添加 `--ignore-engines`。
--------------------------------------------------------------------------------
/docs/Lifecycle.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 生命周期
4 | 下图展示了 Fastify 的内部生命周期。
5 | 每个节点右边的分支为生命周期的下一阶段,左边的则是上一个生命周期抛出错误时产生的错误码 *(请注意 Fastify 会自动处理所有的错误)*。
6 |
7 | ```
8 | Incoming Request
9 | │
10 | └─▶ Routing
11 | │
12 | └─▶ Instance Logger
13 | │
14 | 4**/5** ◀─┴─▶ onRequest Hook
15 | │
16 | 4**/5** ◀─┴─▶ preParsing Hook
17 | │
18 | 4**/5** ◀─┴─▶ Parsing
19 | │
20 | 4**/5** ◀─┴─▶ preValidation Hook
21 | │
22 | 400 ◀─┴─▶ Validation
23 | │
24 | 4**/5** ◀─┴─▶ preHandler Hook
25 | │
26 | 4**/5** ◀─┴─▶ User Handler
27 | │
28 | └─▶ Reply
29 | │
30 | 4**/5** ◀─┴─▶ preSerialization Hook
31 | │
32 | └─▶ onSend Hook
33 | │
34 | 4**/5** ◀─┴─▶ Outgoing Response
35 | │
36 | └─▶ onResponse Hook
37 | ```
38 |
39 | 在`用户编写的处理函数`执行前或执行时,你可以调用 `reply.hijack()` 以使得 Fastify:
40 | - 终止运行所有钩子及用户的处理函数
41 | - 不再自动发送响应
42 |
43 | 特别注意 (*):假如使用了 `reply.raw` 来发送响应,则 `onResponse` 依旧会执行。
44 |
45 | ## 响应生命周期
46 |
47 | 不管用户如何处理请求,结果无非以下几种:
48 |
49 | - 异步函数中返回 payload
50 | - 异步函数中抛出 `Error`
51 | - 同步函数中发送 payload
52 | - 同步函数中发送 `Error` 实例
53 |
54 | 当响应被劫持时 (即调用了 `reply.hijack()`) 会跳过之后的步骤,否则,响应被提交后的数据流向如下:
55 |
56 | ```
57 | ★ schema validation Error
58 | │
59 | └─▶ schemaErrorFormatter
60 | │
61 | reply sent ◀── JSON ─┴─ Error instance
62 | │
63 | │ ★ throw an Error
64 | ★ send or return │ │
65 | │ │ │
66 | │ ▼ │
67 | reply sent ◀── JSON ─┴─ Error instance ──▶ setErrorHandler ◀─────┘
68 | │
69 | reply sent ◀── JSON ─┴─ Error instance ──▶ onError Hook
70 | │
71 | └─▶ reply sent
72 | ```
73 |
74 | 注:`reply sent` 意味着 JSON payload 将会如下被序列化:
75 |
76 | - 通过[响应序列化方法](Server.md#setreplyserializer) (如有设置)
77 | - 或当为返回的 HTTP 状态码设置了 JSON schema 时,通过[序列化函数生成器](Server.md#setserializercompiler)
78 | - 或通过默认的 `JSON.stringify` 函数
--------------------------------------------------------------------------------
/docs/Logging.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 日志
4 |
5 | 日志默认关闭,你可以在创建 Fastify 实例时传入 `{ logger: true }` 或者 `{ logger: { level: 'info' } }` 选项来开启它。要注意的是,日志无法在运行时启用。为此,我们使用了
6 | [abstract-logging](https://www.npmjs.com/package/abstract-logging)。
7 |
8 | Fastify 专注于性能,因此使用了 [pino](https://github.com/pinojs/pino) 作为日志工具。默认的日志级别为 `'info'`。
9 |
10 | 开启日志相当简单:
11 |
12 | ```js
13 | const fastify = require('fastify')({
14 | logger: true
15 | })
16 |
17 | fastify.get('/', options, function (request, reply) {
18 | request.log.info('Some info about the current request')
19 | reply.send({ hello: 'world' })
20 | })
21 | ```
22 |
23 | 在路由函数之外,你可以通过 Fastify 实例上挂载的 Pino 实例来记录日志:
24 | ```js
25 | fastify.log.info('Something important happened!');
26 | ```
27 |
28 | 如果你想为日志配置选项,直接将选项传递给 Fastify 实例就可以了。
29 | 你可以在 [Pino 的文档](https://github.com/pinojs/pino/blob/master/docs/api.md#pinooptions-stream)中找到全部选项。如果你想指定文件地址,可以:
30 |
31 | ```js
32 | const fastify = require('fastify')({
33 | logger: {
34 | level: 'info',
35 | file: '/path/to/file' // 将调用 pino.destination()
36 | }
37 | })
38 | fastify.get('/', options, function (request, reply) {
39 | request.log.info('Some info about the current request')
40 | reply.send({ hello: 'world' })
41 | })
42 | ```
43 |
44 | 如果需要向 Pino 传送自定义流 (stream),仅需在 `logger` 对象中添加 `stream` 一项即可。
45 |
46 | ```js
47 | const split = require('split2')
48 | const stream = split(JSON.parse)
49 |
50 | const fastify = require('fastify')({
51 | logger: {
52 | level: 'info',
53 | stream: stream
54 | }
55 | })
56 | ```
57 |
58 |
59 | 默认情况下,Fastify 给每个请求分配了一个 ID 以便跟踪。如果头部存在 "request-id" 即使用该值,否则会生成一个新的增量 ID。你可以通过 Fastify 工厂函数的 [`requestIdHeader`](Server.md#factory-request-id-header) 与 [`genReqId`](Server.md#genreqid) 来进行自定义。
60 |
61 | 默认的日志工具使用标准的序列化工具,生成包括 `req`、`res` 与 `err` 属性在内的序列化对象。`req` 对象是 Fastify [`Request`](./Request.md) 对象,而 `res` 则是 Fastify [`Reply`](./Reply.md) 对象。可以借由指定自定义的序列化工具来改变这一行为。
62 | ```js
63 | const fastify = require('fastify')({
64 | logger: {
65 | serializers: {
66 | req (request) {
67 | return { url: request.url }
68 | }
69 | }
70 | }
71 | })
72 | ```
73 | 响应的 payload 与 header 可以按如下方式记录日志 (即便这是*不推荐*的做法):
74 |
75 | ```js
76 | const fastify = require('fastify')({
77 | logger: {
78 | prettyPrint: true,
79 | serializers: {
80 | res (reply) {
81 | // 默认
82 | return {
83 | statusCode: reply.statusCode
84 | }
85 | },
86 | req (request) {
87 | return {
88 | method: request.method,
89 | url: request.url,
90 | path: request.path,
91 | parameters: request.parameters,
92 | // 记录 header 可能会触犯隐私法律,例如 GDPR (译注:General Data Protection Regulation)。你应该用 "redact" 选项来移除敏感的字段。此外,验证数据也可能在日志中泄露。
93 | headers: request.headers
94 | };
95 | }
96 | }
97 | }
98 | });
99 | ```
100 | **注**:在 `req` 方法中,body 无法被序列化。因为请求是在创建子日志时就序列化了,而此时 body 尚未被解析。
101 |
102 | 以下是记录 `req.body` 的一个方法
103 |
104 | ```js
105 | app.addHook('preHandler', function (req, reply, done) {
106 | if (req.body) {
107 | req.log.info({ body: req.body }, 'parsed body')
108 | }
109 | done()
110 | })
111 | ```
112 |
113 | *Pino 之外的日志工具会忽略该选项。*
114 |
115 | 你还可以提供自定义的日志实例。将实例传入,取代配置选项即可。提供的示例必须实现 Pino 的接口,换句话说,便是拥有下列方法:
116 | `info`、`error`、`debug`、`fatal`、`warn`、`trace`、`child`。
117 |
118 | 示例:
119 |
120 | ```js
121 | const log = require('pino')({ level: 'info' })
122 | const fastify = require('fastify')({ logger: log })
123 |
124 | log.info('does not have request information')
125 |
126 | fastify.get('/', function (request, reply) {
127 | request.log.info('includes request information, but is the same logger instance as `log`')
128 | reply.send({ hello: 'world' })
129 | })
130 | ```
131 |
132 | *当前请求的日志实例在[生命周期](Lifecycle.md)的各部分均可使用。*
133 |
134 | ## 日志修订
135 |
136 | [Pino](https://getpino.io) 支持低开销的日志修订,以隐藏特定内容。
137 | 举例来说,出于安全方面的考虑,我们也许想在 HTTP header 的日志中隐藏 `Authorization` 这一个 header:
138 |
139 | ```js
140 | const fastify = Fastify({
141 | logger: {
142 | stream: stream,
143 | redact: ['req.headers.authorization'],
144 | level: 'info',
145 | serializers: {
146 | req (request) {
147 | return {
148 | method: request.method,
149 | url: request.url,
150 | headers: request.headers,
151 | hostname: request.hostname,
152 | remoteAddress: request.ip,
153 | remotePort: request.socket.remotePort
154 | }
155 | }
156 | }
157 | }
158 | })
159 | ```
160 |
161 | 更多信息请看 https://getpino.io/#/docs/redaction。
162 |
--------------------------------------------------------------------------------
/docs/Middleware.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 中间件
4 |
5 | 从 3.0.0 版本开始,Fastify 便不再内建地支持中间件了,你需要通过插件例如 [`fastify-express`](https://github.com/fastify/fastify-express) 或 [`middie`](https://github.com/fastify/middie) 来使用它们。
6 |
7 | 以下是通过 [`fastify-express`](https://github.com/fastify/fastify-express) 插件,来使用 express 中间件的示例:
8 |
9 | ```js
10 | await fastify.register(require('fastify-express'))
11 | fastify.use(require('cors')())
12 | fastify.use(require('dns-prefetch-control')())
13 | fastify.use(require('frameguard')())
14 | fastify.use(require('hsts')())
15 | fastify.use(require('ienoopen')())
16 | fastify.use(require('x-xss-protection')())
17 | ```
18 |
19 | 或者通过 [`middie`](https://github.com/fastify/middie),它提供了对简单的 express 风格的中间件的支持,但性能更佳:
20 |
21 | ```js
22 | await fastify.register(require('middie'))
23 | fastify.use(require('cors')())
24 | ```
25 |
26 | ### 替代
27 |
28 | Fastify 提供了最常用中间件的替代品,例如:[`fastify-helmet`](https://github.com/fastify/fastify-helmet) 之于 [`helmet`](https://github.com/helmetjs/helmet),[`fastify-cors`](https://github.com/fastify/fastify-cors) 之于 [`cors`](https://github.com/expressjs/cors),以及 [`fastify-static`](https://github.com/fastify/fastify-static) 之于 [`serve-static`](https://github.com/expressjs/serve-static)。
--------------------------------------------------------------------------------
/docs/Migration-Guide-V3.md:
--------------------------------------------------------------------------------
1 | # 迁移到 V3
2 |
3 | 本文帮助你从 Fastify v2 迁移到 v3。
4 |
5 | 开始之前,请确保所有 v2 中不推荐用法的警示都已修复。v2 的这些特性在新版都已被移除,升级后你将不能使用它们。([#1750](https://github.com/fastify/fastify/pull/1750))
6 |
7 | ## 重大改动
8 |
9 | ### 中间件支持 ([#2014](https://github.com/fastify/fastify/pull/2014))
10 |
11 | 从 Fastify v3 开始,框架本身便不再支持中间件功能了。
12 |
13 | 要使用 Express 的中间件的话,请安装 [`fastify-express`](https://github.com/fastify/fastify-express) 或 [`middie`](https://github.com/fastify/middie)。
14 |
15 | **v2:**
16 |
17 | ```js
18 | // 在 Fastify v2 中使用 Express 的 `cors` 中间件。
19 | fastify.use(require('cors')());
20 | ```
21 |
22 | **v3:**
23 |
24 | ```js
25 | // 在 Fastify v3 中使用 Express 的 `cors` 中间件。
26 | await fastify.register(require('fastify-express'));
27 | fastify.use(require('cors')());
28 | ```
29 |
30 | ### 日志序列化 ([#2017](https://github.com/fastify/fastify/pull/2017))
31 |
32 | 日志的[序列化器](Logging.md)得到了升级,现在它接受 Fastify 的 [`Request`](Request.md) 和 [`Reply`](Reply.md) 对象,而非原生的对象。
33 |
34 | 任何依赖于原生对象而非 Fastify 对象上的 `request` 或 `reply` 属性的自定义的序列化器,都应当升级。
35 |
36 | **v2:**
37 |
38 | ```js
39 | const fastify = require('fastify')({
40 | logger: {
41 | serializers: {
42 | res(res) {
43 | return {
44 | statusCode: res.statusCode,
45 | customProp: res.customProp
46 | };
47 | }
48 | }
49 | }
50 | });
51 | ```
52 |
53 | **v3:**
54 |
55 | ```js
56 | const fastify = require('fastify')({
57 | logger: {
58 | serializers: {
59 | res(reply) {
60 | return {
61 | statusCode: reply.statusCode, // 无需更改
62 | customProp: reply.raw.customProp // 从 res 对象 (译注:即 Node.js 原生的响应对象,此处为 raw) 中记录属性
63 | };
64 | }
65 | }
66 | }
67 | });
68 | ```
69 |
70 | ### schema 代入 (schema substitution) ([#2023](https://github.com/fastify/fastify/pull/2023))
71 |
72 | 非标准`替换方式`的支持被移除了,取而代之的是符合 JSON Schema 标准的 `$ref` 方案。要更好地理解这一改变,请阅读[《Fastify v3 的验证与序列化》](https://dev.to/eomm/validation-and-serialization-in-fastify-v3-2e8l)一文。
73 |
74 | **v2:**
75 |
76 | ```js
77 | const schema = {
78 | body: 'schemaId#'
79 | };
80 | fastify.route({ method, url, schema, handler });
81 | ```
82 |
83 | **v3:**
84 |
85 | ```js
86 | const schema = {
87 | body: {
88 | $ref: 'schemaId#'
89 | }
90 | };
91 | fastify.route({ method, url, schema, handler });
92 | ```
93 |
94 | ### schema 验证选项 ([#2023](https://github.com/fastify/fastify/pull/2023))
95 |
96 | 为了未来工具的改善,`setSchemaCompiler` 和 `setSchemaResolver` 被替换成了 `setValidatorCompiler`。要更好地理解这一改变,请阅读[《Fastify v3 的验证与序列化》](https://dev.to/eomm/validation-and-serialization-in-fastify-v3-2e8l)一文。
97 |
98 | **v2:**
99 |
100 | ```js
101 | const fastify = Fastify();
102 | const ajv = new AJV();
103 | ajv.addSchema(schemaA);
104 | ajv.addSchema(schemaB);
105 |
106 | fastify.setSchemaCompiler(schema => ajv.compile(schema));
107 | fastify.setSchemaResolver(ref => ajv.getSchema(ref).schema);
108 | ```
109 |
110 | **v3:**
111 |
112 | ```js
113 | const fastify = Fastify();
114 | const ajv = new AJV();
115 | ajv.addSchema(schemaA);
116 | ajv.addSchema(schemaB);
117 |
118 | fastify.setValidatorCompiler(({ schema, method, url, httpPart }) =>
119 | ajv.compile(schema)
120 | );
121 | ```
122 |
123 | ### preParsing 钩子的行为 ([#2286](https://github.com/fastify/fastify/pull/2286))
124 |
125 | 为了支持针对请求 payload 的操作,从 Fastify v3 开始,`preParsing` 钩子的行为发生了微小的变化。
126 |
127 | 该钩子现在有一个额外的参数,`payload`,因此,新的函数签名是 `fn(request, reply, payload, done)` 或 `async fn(request, reply, payload)`。
128 |
129 | 钩子可以通过 `done(null, stream)` 回调,或 async 函数返回一个 stream。
130 |
131 | 如果返回了新的 stream,那么在之后的钩子里,这个新的 stream 将代替原有的 stream。这种做法的一个用途是处理经过压缩的请求。
132 |
133 | 新的 stream 还应当添加 `receivedEncodedLength` 属性,来反映客户端数据的真实大小。举例而言,假如请求被压缩了,那么该属性便是压缩后的 payload 的大小。该属性可以 (且应当) 在 `data` 事件中动态更新。
134 |
135 | 原先 Fastify v2 的语法仍然受支持,但不推荐使用。
136 |
137 | ### 钩子的行为 ([#2004](https://github.com/fastify/fastify/pull/2004))
138 |
139 | 为了支持钩子的封装,从 Fastify v3 开始,`onRoute` 与 `onRegister` 钩子的行为发生了微小的变化。
140 |
141 | - `onRoute` - 现在改为了异步调用,且在同一个封装的作用域内会继承。因此,你得在注册其他插件 _之前_ 注册该钩子。
142 | - `onRegister` - 和 onRoute 一样。唯一区别在于现在第一次的调用者不是框架本身了,而是首个注册的插件。
143 |
144 | ### Content Type 解析器的语法 ([#2286](https://github.com/fastify/fastify/pull/2286))
145 |
146 | 在 Fastify v3 中,Content Type 解析器现在有了单一函数签名。
147 |
148 | 新的签名是 `fn(request, payload, done)` 或 `async fn(request, payload)`。注意现在 `request` 是 Fastify 的请求对象,而不是 `IncomingMessage` 了。默认情况下,payload 是一个 stream。如果在 `addContentTypeParser` 中使用了 `parseAs` 选项,那么 `payload` 会被当做该选项的值来对待 (string 或 buffer)。
149 |
150 | 原先的函数签名 `fn(req, [done])` 或 `fn(req, payload, [done])` (这里 `req` 是 `IncomingMessage`) 仍然受支持,但不推荐使用。
151 |
152 | ### TypeScript 支持
153 |
154 | 版本 3 的类型系统发生了改变。新的系统带来了泛型约束 (generic constraining) 与默认值,以及定义请求 body,querystring 等 schema 的新方式!
155 |
156 | **v2:**
157 |
158 | ```ts
159 | interface PingQuerystring {
160 | foo?: number;
161 | }
162 |
163 | interface PingParams {
164 | bar?: string;
165 | }
166 |
167 | interface PingHeaders {
168 | a?: string;
169 | }
170 |
171 | interface PingBody {
172 | baz?: string;
173 | }
174 |
175 | server.get(
176 | '/ping/:bar',
177 | opts,
178 | (request, reply) => {
179 | console.log(request.query); // 类型为 `PingQuerystring`
180 | console.log(request.params); // 类型为 `PingParams`
181 | console.log(request.headers); // 类型为 `PingHeaders`
182 | console.log(request.body); // 类型为 `PingBody`
183 | }
184 | );
185 | ```
186 |
187 | **v3:**
188 |
189 | ```ts
190 | server.get<{
191 | Querystring: PingQuerystring;
192 | Params: PingParams;
193 | Headers: PingHeaders;
194 | Body: PingBody;
195 | }>('/ping/:bar', opts, async (request, reply) => {
196 | console.log(request.query); // 类型为 `PingQuerystring`
197 | console.log(request.params); // 类型为 `PingParams`
198 | console.log(request.headers); // 类型为 `PingHeaders`
199 | console.log(request.body); // 类型为 `PingBody`
200 | });
201 | ```
202 |
203 | ### 管理未捕获异常 ([#2073](https://github.com/fastify/fastify/pull/2073))
204 |
205 | 在同步的路由方法里,一旦一个错误被抛出,服务器将会如设定的那样崩溃,且不调用 `.setErrorHandler()` 方法。现在这一行为发生了改变,所有在同步或异步的路由中未捕获的异常,都将得到控制。
206 |
207 | **v2:**
208 |
209 | ```js
210 | fastify.setErrorHandler((error, request, reply) => {
211 | // 不会调用
212 | reply.send(error)
213 | })
214 | fastify.get('/', (request, reply) => {
215 | const maybeAnArray = request.body.something ? [] : 'I am a string'
216 | maybeAnArray.substr() // 抛错:[].substr is not a function,同时服务器崩溃
217 | })
218 | ```
219 |
220 | **v3:**
221 |
222 | ```js
223 | fastify.setErrorHandler((error, request, reply) => {
224 | // 会调用
225 | reply.send(error)
226 | })
227 | fastify.get('/', (request, reply) => {
228 | const maybeAnArray = request.body.something ? [] : 'I am a string'
229 | maybeAnArray.substr() // 抛错:[].substr is not a function,但错误得到控制
230 | })
231 | ```
232 |
233 | ## 更多特性与改善
234 |
235 | - 不管如何注册钩子,它们总拥有一致的上下文 ([#2005](https://github.com/fastify/fastify/pull/2005))
236 | - 推荐使用 [`request.raw`](Request.md) 及 [`reply.raw`](Reply.md),而非 `request.req` 和 `reply.res` ([#2008](https://github.com/fastify/fastify/pull/2008))
237 | - 移除 `modifyCoreObjects` 选项 ([#2015](https://github.com/fastify/fastify/pull/2015))
238 | - 添加 [`connectionTimeout`](Server.md#factory-connection-timeout) 选项 ([#2086](https://github.com/fastify/fastify/pull/2086))
239 | - 添加 [`keepAliveTimeout`](Server.md#factory-keep-alive-timeout) 选项 ([#2086](https://github.com/fastify/fastify/pull/2086))
240 | - [插件](Plugins.md#async-await)支持 async-await ([#2093](https://github.com/fastify/fastify/pull/2093))
241 | - 支持将对象作为错误抛出 ([#2134](https://github.com/fastify/fastify/pull/2134))
--------------------------------------------------------------------------------
/docs/Plugins-Guide.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | # 插件漫游指南
4 | 首先, `不要恐慌`!
5 |
6 | Fastify 从一开始就搭建成非常模块化的系统. 我们搭建了非常强健的 API 来允许你创建命名空间, 来添加工具方法. Fastify 创建的封装模型可以让你在任何时候将你的应用分割成不同的微服务, 而无需重构整个应用.
7 |
8 | **内容清单**
9 | - [注册器](#register)
10 | - [装饰器](#decorators)
11 | - [钩子方法](#hooks)
12 | - [如何处理封装与分发](#distribution)
13 | - [ESM 的支持](#esm-support)
14 | - [错误处理](#handle-errors)
15 | - [自定义错误](#custom-errors)
16 | - [发布提醒](#emit-warnings)
17 | - [开始!](#start)
18 |
19 |
20 | ## 注册器
21 | 就像在 JavaScript 万物都是对象, 在 Fastify 万物都是插件.
22 | 你的路由, 你的工具方法等等都是插件. 无论添加什么功能的插件, 你都可以使用 Fastify 优秀又独一无二的 API: [`register`](Plugins.md).
23 | ```js
24 | fastify.register(
25 | require('./my-plugin'),
26 | { options }
27 | )
28 | ```
29 | `register` 创建一个新的 Fastify 上下文, 这意味着如果你对 Fastify 的实例做任何改动, 这些改动不会反映到上下文的父级上. 换句话说, 封装!
30 |
31 | *为什么封装这么重要?*
32 | 那么, 假设你创建了一个具有开创性的初创公司, 你会怎么做? 你创建了一个包含所有东西的 API 服务器, 所有东西都在同一个地方, 一个庞然大物!
33 | 现在, 你增长得非常迅速, 想要改变架构去尝试微服务. 通常这意味着非常多的工作, 因为交叉依赖和缺少关注点的分离.
34 | Fastify 在这个层面上可以帮助你很多, 多亏了封装模型, 它完全避免了交叉依赖, 并且帮助你将组织成高聚合的代码块.
35 |
36 | *让我们回到如何正确地使用 `register`.*
37 | 插件必须输出一个有以下参数的方法
38 | ```js
39 | module.exports = function (fastify, options, done) {}
40 | ```
41 | `fastify` 就是封装的 Fastify 实例, `options` 就是选项对象, 而 `done` 是一个在插件准备好了之后**必须**要调用的方法.
42 |
43 | Fastify 的插件模型是完全可重入的和基于图(数据结构)的, 它能够处理任何异步代码并且保证插件的加载顺序, 甚至是关闭顺序! *如何做到的?* 很高兴你发问了, 查看下 [`avvio`](https://github.com/mcollina/avvio)! Fastify 在 `.listen()`, `.inject()` 或者 `.ready()` 被调用了之后开始加载插件.
44 |
45 | 在插件里面你可以做任何想要做的事情, 注册路由, 工具方法 (我们马上会看到这个) 和进行嵌套的注册, 只要记住当所有都设置好了后调用 `done`!
46 | ```js
47 | module.exports = function (fastify, options, done) {
48 | fastify.get('/plugin', (request, reply) => {
49 | reply.send({ hello: 'world' })
50 | })
51 |
52 | done()
53 | }
54 | ```
55 |
56 | 那么现在你已经知道了如何使用 `register` API 并且知道它是怎么工作的, 但我们如何给 Fastify 添加新的功能, 并且分享给其他的开发者?
57 |
58 |
59 | ## 装饰器
60 | 好了, 假设你写了一个非常好的工具方法, 因此你决定在你所有的代码里都能够用这个方法. 你改怎么做? 可能是像以下代码一样:
61 | ```js
62 | // your-awesome-utility.js
63 | module.exports = function (a, b) {
64 | return a + b
65 | }
66 | ```
67 | ```js
68 | const util = require('./your-awesome-utility')
69 | console.log(util('that is ', 'awesome'))
70 | ```
71 | 现在你需要在所有需要这个方法的文件中引入它. (别忘了你可能在测试中也需要它).
72 |
73 | Fastify 提供了一个更优雅的方法, *装饰器*.
74 | 创建一个装饰器非常简单, 只要使用 [`decorate`](Decorators.md) API:
75 | ```js
76 | fastify.decorate('util', (a, b) => a + b)
77 | ```
78 | 现在你可以在任意地方通过 `fastify.util` 调用你的方法, 甚至在你的测试中.
79 | 这里神奇的是: 你还记得之前我们讨论的封装? 同时使用 `register` 和 `decorate` 可以实现, 让我用例子来阐明这个事情:
80 | ```js
81 | fastify.register((instance, opts, done) => {
82 | instance.decorate('util', (a, b) => a + b)
83 | console.log(instance.util('that is ', 'awesome'))
84 |
85 | done()
86 | })
87 |
88 | fastify.register((instance, opts, done) => {
89 | console.log(instance.util('that is ', 'awesome')) // 这里会抛错
90 |
91 | done()
92 | })
93 | ```
94 | 在第二个注册器中调用 `instance.util` 会抛错, 因为 `util` 只存在第一个注册器的上下文中.
95 | 让我们更深入地看一下: 当使用 `register` API 每次都会创建一个新的上下文而且这避免了上文提到的这个状况.
96 |
97 | 但是注意, 封装只会在父级和同级中有效, 不会在子级中有效.
98 | ```js
99 | fastify.register((instance, opts, done) => {
100 | instance.decorate('util', (a, b) => a + b)
101 | console.log(instance.util('that is ', 'awesome'))
102 |
103 | fastify.register((instance, opts, done) => {
104 | console.log(instance.util('that is ', 'awesome')) // 这里不会抛错
105 | done()
106 | })
107 |
108 | done()
109 | })
110 |
111 | fastify.register((instance, opts, done) => {
112 | console.log(instance.util('that is ', 'awesome')) // 这里会抛错
113 |
114 | done()
115 | })
116 | ```
117 | *PS: 如果你需要全局的工具方法, 请注意要声明在应用根作用域上. 或者你可以使用 `fastify-plugin` 工具, [参考](#distribution).*
118 |
119 | `decorate` 不是唯一可以用来扩展服务器的功能的 API, 你还可以使用 `decorateRequest` 和 `decorateReply`.
120 |
121 | *`decorateRequest` 和 `decorateReply`? 为什么我们已经有了 `decorate` 还需要它们?*
122 | 好问题, 是为了让开发者更方便地使用 Fastify. 让我们看看这个例子:
123 | ```js
124 | fastify.decorate('html', payload => {
125 | return generateHtml(payload)
126 | })
127 |
128 | fastify.get('/html', (request, reply) => {
129 | reply
130 | .type('text/html')
131 | .send(fastify.html({ hello: 'world' }))
132 | })
133 | ```
134 | 这个可行, 但可以变得更好!
135 | ```js
136 | fastify.decorateReply('html', function (payload) {
137 | this.type('text/html') // this 是 'Reply' 对象
138 | this.send(generateHtml(payload))
139 | })
140 |
141 | fastify.get('/html', (request, reply) => {
142 | reply.html({ hello: 'world' })
143 | })
144 | ```
145 |
146 | 你可以对 `request` 对象做同样的事:
147 | ```js
148 | fastify.decorate('getHeader', (req, header) => {
149 | return req.headers[header]
150 | })
151 |
152 | fastify.addHook('preHandler', (request, reply, done) => {
153 | request.isHappy = fastify.getHeader(request.raw, 'happy')
154 | done()
155 | })
156 |
157 | fastify.get('/happiness', (request, reply) => {
158 | reply.send({ happy: request.isHappy })
159 | })
160 | ```
161 | 这个也可行, 但可以变得更好!
162 | ```js
163 | fastify.decorateRequest('setHeader', function (header) {
164 | this.isHappy = this.headers[header]
165 | })
166 |
167 | fastify.decorateRequest('isHappy', false) // 这会添加到 Request 对象的原型中, 好快!
168 |
169 | fastify.addHook('preHandler', (request, reply, done) => {
170 | request.setHeader('happy')
171 | done()
172 | })
173 |
174 | fastify.get('/happiness', (request, reply) => {
175 | reply.send({ happy: request.isHappy })
176 | })
177 | ```
178 |
179 | 我们见识了如何扩展服务器的功能并且如何处理封装系统, 但是假如你需要加一个方法, 每次在服务器 "[emits](Lifecycle.md)" 事件的时候执行这个方法, 该怎么做?
180 |
181 |
182 | ## 钩子方法
183 | 你刚刚构建了工具方法, 现在你需要在每个请求的时候都执行这个方法, 你大概会这样做:
184 | ```js
185 | fastify.decorate('util', (request, key, value) => { request[key] = value })
186 |
187 | fastify.get('/plugin1', (request, reply) => {
188 | fastify.util(request, 'timestamp', new Date())
189 | reply.send(request)
190 | })
191 |
192 | fastify.get('/plugin2', (request, reply) => {
193 | fastify.util(request, 'timestamp', new Date())
194 | reply.send(request)
195 | })
196 | ```
197 | 我想大家都同意这个代码是很糟的. 代码重复, 可读性差并且不能扩展.
198 |
199 | 那么你该怎么消除这个问题呢? 是的, 使用[钩子方法](Hooks.md)!
200 | ```js
201 | fastify.decorate('util', (request, key, value) => { request[key] = value })
202 |
203 | fastify.addHook('preHandler', (request, reply, done) => {
204 | fastify.util(request, 'timestamp', new Date())
205 | done()
206 | })
207 |
208 | fastify.get('/plugin1', (request, reply) => {
209 | reply.send(request)
210 | })
211 |
212 | fastify.get('/plugin2', (request, reply) => {
213 | reply.send(request)
214 | })
215 | ```
216 | 现在每个请求都会运行工具方法, 很显然你可以注册任意多的需要的钩子方法.
217 | 有时, 你希望只在一个路由子集中执行钩子方法, 这个怎么做到? 对了, 封装!
218 |
219 | ```js
220 | fastify.register((instance, opts, done) => {
221 | instance.decorate('util', (request, key, value) => { request[key] = value })
222 |
223 | instance.addHook('preHandler', (request, reply, done) => {
224 | instance.util(request, 'timestamp', new Date())
225 | done()
226 | })
227 |
228 | instance.get('/plugin1', (request, reply) => {
229 | reply.send(request)
230 | })
231 |
232 | done()
233 | })
234 |
235 | fastify.get('/plugin2', (request, reply) => {
236 | reply.send(request)
237 | })
238 | ```
239 | 现在你的钩子方法只会在第一个路由中运行!
240 |
241 | 你可能已经注意到, `request` and `reply` 不是标准的 Nodejs *request* 和 *response* 对象, 而是 Fastify 对象.
242 |
243 |
244 | ## 如何处理封装与分发
245 | 完美, 现在你知道了(几乎)所有的扩展 Fastify 的工具. 但可能你遇到了一个大问题: 如何分发你的代码?
246 |
247 | 我们推荐将所有代码包裹在一个`注册器`中分发, 这样你的插件可以支持异步启动 *(`decorate` 是一个同步 API)*, 例如建立数据库链接.
248 |
249 | *等等? 你不是告诉我 `register` 会创建封装的上下文, 那么我创建的不是就外层不可见了?*
250 | 是的, 我是说过. 但我没告诉你的是, 你可以通过 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 模块告诉 Fastify 不要进行封装.
251 | ```js
252 | const fp = require('fastify-plugin')
253 | const dbClient = require('db-client')
254 |
255 | function dbPlugin (fastify, opts, done) {
256 | dbClient.connect(opts.url, (err, conn) => {
257 | fastify.decorate('db', conn)
258 | done()
259 | })
260 | }
261 |
262 | module.exports = fp(dbPlugin)
263 | ```
264 | 你还可以告诉 `fastify-plugin` 去检查安装的 Fastify 版本, 万一你需要特定的 API.
265 |
266 | 正如前面所述,Fastify 在 `.listen()`、`.inject()` 以及 `.ready()` 被调用,也即插件被声明 __之后__ 才开始加载插件。这么一来,即使插件通过 [`decorate`](Decorators.md) 向外部的 Fastify 实例注入了变量,在调用 `.listen()`、`.inject()` 和 `.ready()` 之前,这些变量是获取不到的。
267 |
268 | 当你需要在 `register` 方法的 `options` 参数里使用另一个插件注入的变量时,你可以向 `options` 传递一个函数参数,而不是对象:
269 | ```js
270 | const fastify = require('fastify')()
271 | const fp = require('fastify-plugin')
272 | const dbClient = require('db-client')
273 |
274 | function dbPlugin (fastify, opts, done) {
275 | dbClient.connect(opts.url, (err, conn) => {
276 | fastify.decorate('db', conn)
277 | done()
278 | })
279 | }
280 |
281 | fastify.register(fp(dbPlugin), { url: 'https://example.com' })
282 | fastify.register(require('your-plugin'), parent => {
283 | return { connection: parent.db, otherOption: 'foo-bar' }
284 | })
285 | ```
286 | 在上面的例子中,`register` 方法的第二个参数的 `parent` 变量是注册了插件的**外部 Fastify 实例**的一份拷贝。这就意味着我们可以获取到之前声明的插件所注入的变量了。
287 |
288 |
289 | ## ESM 的支持
290 |
291 | 自 [Node.js `v13.3.0`](https://nodejs.org/api/esm.html) 开始, ESM 也被支持了!写插件时,你只需要将其作为 ESM 模块导出即可!
292 |
293 | ```js
294 | // plugin.mjs
295 | async function plugin (fastify, opts) {
296 | fastify.get('/', async (req, reply) => {
297 | return { hello: 'world' }
298 | })
299 | }
300 |
301 | export default plugin
302 | ```
303 |
304 | __注意__:Fastify 不支持具名导入 ESM 模块,但支持 `default` 导入。
305 |
306 | ```js
307 | // server.mjs
308 | import Fastify from 'fastify'
309 |
310 | const fastify = Fastify()
311 |
312 | ///...
313 |
314 | fastify.listen(3000, (err, address) => {
315 | if (err) {
316 | fastify.log.error(err)
317 | process.exit(1)
318 | }
319 | })
320 | ```
321 |
322 |
323 | ## 错误处理
324 | 你的插件也可能在启动的时候失败. 或许你预料到这个并且在这种情况下有特定的处理逻辑. 你该怎么实现呢?
325 | `after` API 就是你需要的. `after` 注册一个回调, 在注册之后就会调用这个回调, 它可以有三个参数.
326 | 回调会基于不同的参数而变化:
327 |
328 | 1. 如果没有参数并且有个错误, 这个错误会传递到下一个错误处理.
329 | 1. 如果有一个参数, 这个参数就是错误对象.
330 | 1. 如果有两个参数, 第一个是错误对象, 第二个是完成回调.
331 | 1. 如果有三个参数, 第一个是错误对象, 第二个是顶级上下文(除非你同时指定了服务器和复写, 在这个情况下将会是那个复写的返回), 第三个是完成回调.
332 |
333 | 让我们看看如何使用它:
334 | ```js
335 | fastify
336 | .register(require('./database-connector'))
337 | .after(err => {
338 | if (err) throw err
339 | })
340 | ```
341 |
342 |
343 | ## 自定义错误
344 | 假如你的插件需要暴露自定义的错误,[`fastify-error`](https://github.com/fastify/fastify-error) 能帮助你轻松地在代码或插件中生成一致的错误对象。
345 |
346 | ```js
347 | const createError = require('fastify-error')
348 | const CustomError = createError('ERROR_CODE', 'message')
349 | console.log(new CustomError())
350 | ```
351 |
352 |
353 | ## 发布提醒
354 | 假如你要提示用户某个 API 不被推荐,或某个特殊场景需要注意,你可以使用 [`fastify-warning`](https://github.com/fastify/fastify-warning)。
355 |
356 | ```js
357 | const warning = require('fastify-warning')()
358 | warning.create('FastifyDeprecation', 'FST_ERROR_CODE', 'message')
359 | warning.emit('FST_ERROR_CODE')
360 | ```
361 |
362 |
363 | ## 开始!
364 | 太棒了, 现在你已经知道了所有创建插件需要的关于 Fastify 和它的插件系统的知识, 如果你写了插件请告诉我们! 我们会将它加入到 [*生态*](https://github.com/fastify/fastify#ecosystem) 章节中!
365 |
366 | 如果你想要看看真正的插件例子, 查看:
367 | - [`point-of-view`](https://github.com/fastify/point-of-view)
368 | 给 Fastify 提供模版 (*ejs, pug, handlebars, marko*) 支持.
369 | - [`fastify-mongodb`](https://github.com/fastify/fastify-mongodb)
370 | Fastify MongoDB 连接插件, 可以在全局使用同一 MongoDb 连接池.
371 | - [`fastify-multipart`](https://github.com/fastify/fastify-multipart)
372 | Multipart 支持
373 | - [`fastify-helmet`](https://github.com/fastify/fastify-helmet) 重要的安全头部支持
374 |
375 |
376 | *如果感觉还差什么? 告诉我们! :)*
377 |
--------------------------------------------------------------------------------
/docs/Plugins.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 插件
4 | Fastify 允许用户通过插件的方式扩展自身的功能。
5 | 一个插件可以是一组路由,一个服务器[装饰器](Decorators.md)或者其他任意的东西。 在使用一个或者许多插件时,只需要一个 API `register`。
6 |
7 | 默认, `register` 会创建一个 *新的作用域( Scope )*, 这意味着你能够改变 Fastify 实例(通过`decorate`), 这个改变不会反映到当前作用域, 只会影响到子作用域。 这样可以做到插件的*封装*和*继承*, 我们创建了一个*无回路有向图*(DAG), 因此不会有交叉依赖的问题。
8 |
9 | 你已经在[起步](Getting-Started.md#register)部分很直观的看到了怎么使用这个 API。
10 | ```
11 | fastify.register(plugin, [options])
12 | ```
13 |
14 |
15 | ### 插件选项
16 | `fastify.register` 可选参数列表支持一组预定义的 Fastify 可用的参数, 除了当插件使用了 [fastify-plugin](https://github.com/fastify/fastify-plugin)。 选项对象会在插件被调用传递进去, 无论这个插件是否用了 fastify-plugin。 当前支持的选项有:
17 |
18 | + [`日志级别`](Routes.md#custom-log-level)
19 | + [`日志序列化器`](Routes.md#custom-log-serializer)
20 | + [`前缀`](Plugins.md#route-prefixing-options)
21 |
22 | **注意:当使用 fastify-plugin 时,这些选项会被忽略**
23 |
24 | Fastify 有可能在将来会直接支持其他的选项。 因此为了避免冲突, 插件应该考虑给选项加入命名空间。 举个例子, 插件 `foo` 可以像以下代码一样注册:
25 |
26 | ```js
27 | fastify.register(require('fastify-foo'), {
28 | prefix: '/foo',
29 | foo: {
30 | fooOption1: 'value',
31 | fooOption2: 'value'
32 | }
33 | })
34 | ```
35 |
36 | 如果不考虑冲突, 插件可以简化成直接接收对象参数:
37 |
38 | ```js
39 | fastify.register(require('fastify-foo'), {
40 | prefix: '/foo',
41 | fooOption1: 'value',
42 | fooOption2: 'value'
43 | })
44 | ```
45 |
46 | `options` 参数还可以是一个在插件注册时确定的 `函数`,这个函数的第一位参数是 Fastify 实例:
47 |
48 | ```js
49 | const fp = require('fastify-plugin')
50 |
51 | fastify.register(fp((fastify, opts, done) => {
52 | fastify.decorate('foo_bar', { hello: 'world' })
53 |
54 | done()
55 | }))
56 |
57 | // fastify-foo 的 options 参数会是 { hello: 'world' }
58 | fastify.register(require('fastify-foo'), parent => parent.foo_bar)
59 | ```
60 |
61 | 传给函数的 Fastify 实例是插件声明时**外部 Fastify 实例**的最新状态,允许你访问**注册顺序**在前的插件通过 [`decorate`](Decorators.md) 注入的变量。这在需要依赖前置插件对于 Fastify 实例的改动时派得上用场,比如,使用已存在的数据库连接来包装你的插件。
62 |
63 | 请记住,传给函数的 Fastify 实例和传给插件的实例是一样的,不是外部 Fastify 实例的引用,而是拷贝。任何对函数的实例参数的操作结果,都会和在插件函数中操作的结果一致。也就是说,如果调用了 `decorate`,被注入的变量在插件函数中也是可用的,除非你使用 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 包装了这个插件。
64 |
65 |
66 | #### 路由前缀选项
67 | 如果你传入以 `prefix`为 key , `string` 为值的选项, Fastify 会自动为这个插件下所有的路由添加这个前缀, 更多信息可以查询 [这里](Routes.md#route-prefixing).
68 | 注意如果使用了 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 这个选项不会起作用。
69 |
70 |
71 | #### 错误处理
72 | 错误处理是由 [avvio](https://github.com/mcollina/avvio#error-handling) 解决的。
73 | 一个通用的原则, 我们建议在下一个 `after` 或 `ready` 代码块中处理错误, 否则错误将出现在 `listen` 回调里。
74 |
75 | ```js
76 | fastify.register(require('my-plugin'))
77 |
78 | // `after` 将在上一个 `register` 结束后执行
79 | fastify.after(err => console.log(err))
80 |
81 | // `ready` 将在所有 `register` 结束后执行
82 | fastify.ready(err => console.log(err))
83 |
84 | // `listen` 是一个特殊的 `ready`,
85 | // 因此它的执行时机与 `ready` 一致
86 | fastify.listen(3000, (err, address) => {
87 | if (err) console.log(err)
88 | })
89 | ```
90 |
91 |
92 | ### async/await
93 |
94 | `after`、`ready` 与 `listen` 支持 *async/await*,同时 `fastify` 也是一个 [Thenable](https://promisesaplus.com/) 对象。
95 |
96 | ```js
97 | await fastify.register(require('my-plugin'))
98 |
99 | await fastify.after()
100 |
101 | await fastify.ready()
102 |
103 | await fastify.listen(3000)
104 | ```
105 |
106 |
107 | #### ESM 的支持
108 |
109 | 自 [Node.js `v13.3.0`](https://nodejs.org/api/esm.html) 开始, ESM 也被支持了!
110 |
111 | ```js
112 | // main.mjs
113 | import Fastify from 'fastify'
114 | const fastify = Fastify()
115 |
116 | fastify.register(import('./plugin.mjs'))
117 |
118 | fastify.listen(3000, console.log)
119 |
120 | // plugin.mjs
121 | async function plugin (fastify, opts) {
122 | fastify.get('/', async (req, reply) => {
123 | return { hello: 'world' }
124 | })
125 | }
126 |
127 | export default plugin
128 | ```
129 |
130 |
131 | ### 创建插件
132 | 创建插件非常简单, 你只需要创建一个方法, 这个方法接收三个参数: `fastify` 实例、`options` 选项和 `done` 回调。
133 | 例子:
134 | ```js
135 | module.exports = function (fastify, opts, done) {
136 | fastify.decorate('utility', () => {})
137 |
138 | fastify.get('/', handler)
139 |
140 | done()
141 | }
142 | ```
143 | 你也可以在一个 `register` 内部添加其他 `register`:
144 | ```js
145 | module.exports = function (fastify, opts, done) {
146 | fastify.decorate('utility', () => {})
147 |
148 | fastify.get('/', handler)
149 |
150 | fastify.register(require('./other-plugin'))
151 |
152 | done()
153 | }
154 | ```
155 | 有时候, 你需要知道这个服务器何时即将关闭, 例如在你必须关闭数据库连接的时候。 要知道什么时候发生这种情况, 你可以用 [`'onClose'`](Hooks.md#on-close) 钩子。
156 |
157 | 别忘了 `register` 会创建一个新的 Fastify 作用域, 如果你不需要, 阅读下面的章节。
158 |
159 |
160 | ### 处理作用域
161 | 如果你使用 `register` 仅仅是为了通过[`decorate`](Decorators.md)扩展服务器的功能, 你需要告诉 Fastify 不要创建新的上下文, 不然你的改动不会影响其他作用域中的用户。
162 |
163 | 你有两种方式告诉 Fastify 避免创建新的上下文:
164 | - 使用 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 模块
165 | - 使用 `'skip-override'` 隐藏属性
166 |
167 | 我们建议使用 `fastify-plugin` 模块, 因为它是专门用来为你解决这个问题, 并且你可以传一个能够支持的 Fastify 版本范围的参数。
168 | ```js
169 | const fp = require('fastify-plugin')
170 |
171 | module.exports = fp(function (fastify, opts, done) {
172 | fastify.decorate('utility', () => {})
173 | done()
174 | }, '0.x')
175 | ```
176 | 参考 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 文档了解更多这个模块。
177 |
178 | 如果你不用 `fastify-plugin` 模块, 可以使用 `'skip-override'` 隐藏属性, 但我们不推荐这么做。 如果将来 Fastify API 改变了, 你需要去更新你的模块, 如果使用 `fastify-plugin`, 你可以对向后兼容放心。
179 | ```js
180 | function yourPlugin (fastify, opts, done) {
181 | fastify.decorate('utility', () => {})
182 | done()
183 | }
184 | yourPlugin[Symbol.for('skip-override')] = true
185 | module.exports = yourPlugin
186 | ```
187 |
--------------------------------------------------------------------------------
/docs/Recommendations.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 推荐方案
4 |
5 | 本文涵盖了使用 Fastify 的推荐方案及最佳实践。
6 |
7 | * [使用反向代理](#reverseproxy)
8 | * [Kubernetes](#kubernetes)
9 |
10 | ## 使用反向代理
11 |
12 |
13 | Node.js 作为各框架中的先行者,在标准库中提供了易用的 web 服务器。在它现世前,PHP、Python 等语言的使用者,要么需要一个支持该语言的 web 服务器,要么需要一个搭配该语言的 [CGI 网关](cgi)。而 Node.js 能让用户专注于 _直接_ 处理 HTTP 请求的应用本身,这样一来,新的诱惑点变成了处理多个域名的请求、监听多端口 (如 HTTP _和_ HTTPS),接着将应用直接暴露于 Internet 来处理请求。
14 |
15 | Fastify 团队**强烈**地认为上述做法是一种反面模式,是非常不理想的实践:
16 |
17 | 1. 它分离了程序的关注点,增加了不必要的复杂度。
18 | 2. 它限制了程序的[水平拓展](scale-horiz)。
19 |
20 | 请看《[生产环境可用的 Node.js 为何还需要反向代理?][why-use]》一文,这里有更深入的讨论。
21 |
22 | 考虑以下具体案例:
23 |
24 | 1. 应用需要多个实例来处理负载。
25 | 1. 应用需要 TLS 终端 (TLS termination)。
26 | 1. 应用需要将 HTTP 请求转发至 HTTPS。
27 | 1. 应用需要处理多域名。
28 | 1. 应用需要处理静态资源,例如 jpeg 文件。
29 |
30 | 反向代理的解决方案有很多种,例如 AWS 与 GCP,具体根据环境来择用。对于上述的案例,我们可以使用 [HAProxy][haproxy] 或 [Nginx][nginx]。
31 |
32 | ### HAProxy
33 |
34 | ```conf
35 | # global 定义了 HAProxy 实例的基础配置。
36 | global
37 | log /dev/log syslog
38 | maxconn 4096
39 | chroot /var/lib/haproxy
40 | user haproxy
41 | group haproxy
42 |
43 | # 设置 TLS 基础配置。
44 | tune.ssl.default-dh-param 2048
45 | ssl-default-bind-options no-sslv3 no-tlsv10 no-tlsv11
46 | ssl-default-bind-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
47 | ssl-default-server-options no-sslv3 no-tlsv10 no-tlsv11
48 | ssl-default-server-ciphers ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:RSA+AESGCM:RSA+AES:!aNULL:!MD5:!DSS
49 |
50 | # defaults 定义了接下来每个子段落的默认配置,直到出现另一段 defaults。
51 | defaults
52 | log global
53 | mode http
54 | option httplog
55 | option dontlognull
56 | retries 3
57 | option redispatch
58 | # 下面的选项使 haproxy 关闭与后端的连接,而不是保持连接。
59 | # 这么做能减轻 Node 进程发生预期外的连接重置错误。
60 | option http-server-close
61 | maxconn 2000
62 | timeout connect 5000
63 | timeout client 50000
64 | timeout server 50000
65 |
66 | # 压缩特定类型的内容。
67 | compression algo gzip
68 | compression type text/html text/plain text/css application/javascript
69 |
70 | # frontend 定义一个公开的监听器,即客户端所关注的“http 服务器”。
71 | frontend proxy
72 | # 这里的 IP 地址为服务器的_公开_ IP 地址。
73 | # 在这个例子里,我们使用一个私有的地址。
74 | bind 10.0.0.10:80
75 | # 将所有非 TLS 的请求转发至 HTTPS 端口的相同 URL。
76 | redirect scheme https code 308 if !{ ssl_fc }
77 | # 从技术角度讲,这里的 use_backend 指令没有用处,
78 | # 因为我们已经将所有到达该监听器的请求转发至 HTTPS 了。
79 | # 在此提到该指令仅仅是为了示例的完整性。
80 | use_backend default-server
81 |
82 | # 这段 frontend 定义了主要的 TLS 监听器。
83 | # 在此我们定义 TLS 证书,以及如何引流来访的请求。
84 | frontend proxy-ssl
85 | # 本例的 `/etc/haproxy/certs` 文件夹保存了以域名命名的 PEM 格式证书。
86 | # 当 HAProxy 启动时,它会加载该文件夹中的证书,
87 | # 并使用服务器名称指示协议 (SNI) 将证书应用于对应的连接。
88 | bind 10.0.0.10:443 ssl crt /etc/haproxy/certs
89 |
90 | # 定义静态资源处理规则。
91 | # 任何包括 `/static` 路径 (如 `https://one.example.com/static/foo.jpeg`) 的请求,
92 | # 将被重定向至静态资源服务器。
93 | acl is_static path -i -m beg /static
94 | use_backend static-backend if is_static
95 |
96 | # 根据请求的域名,转发至对应的 Node.js 服务器。
97 | # `acl` 开头这行用于匹配主机名,并定义了一个布尔值用于判断匹配与否。
98 | # `use_backend` 这行则在该布尔值为真时进行转发。
99 | acl example1 hdr_sub(Host) one.example.com
100 | use_backend example1-backend if example1
101 |
102 | acl example2 hdr_sub(Host) two.example.com
103 | use_backend example2-backend if example2
104 |
105 | # 最后,我们提供一个后备的重定向,以防上述规则均不适用。
106 | default_backend default-server
107 |
108 | # backend 告诉 HAProxy 去哪里获取请求所需的信息。
109 | # 在此我们定义 Node.js 应用及静态资源等其他服务器的地址。
110 | backend default-server
111 | # 在这个例子中,我们将未匹配域名的请求默认转发到一个能处理所有请求的后端。
112 | # 值得注意的是,后端服务器不需要处理 TLS 请求。
113 | # 这被称为“TLS 终端 (TLS termination)”:TLS 连接在反向代理中即得到处理。
114 | # 代理至有 TLS 请求处理能力的后端也是可行的,但这不在本示例的内容范围之内。
115 | server server1 10.10.10.2:80
116 |
117 | # 通过轮询调度,将 `https://one.example.com` 的请求代理至三个后端服务器。
118 | backend example1-backend
119 | server example1-1 10.10.11.2:80
120 | server example1-2 10.10.11.2:80
121 | server example2-2 10.10.11.3:80
122 |
123 | # 处理 `https://two.example.com` 的请求。
124 | backend example2-backend
125 | server example2-1 10.10.12.2:80
126 | server example2-2 10.10.12.2:80
127 | server example2-3 10.10.12.3:80
128 |
129 | # 处理静态资源请求。
130 | backend static-backend
131 | server static-server1 10.10.9.2:80
132 | ```
133 |
134 | [cgi]: https://en.wikipedia.org/wiki/Common_Gateway_Interface
135 | [scale-horiz]: https://en.wikipedia.org/wiki/Scalability#Horizontal
136 | [why-use]: https://web.archive.org/web/20190821102906/https://medium.com/intrinsic/why-should-i-use-a-reverse-proxy-if-node-js-is-production-ready-5a079408b2ca
137 | [haproxy]: https://www.haproxy.org/
138 |
139 | ### Nginx
140 |
141 | ```nginx
142 | upstream fastify_app {
143 | # 更多信息请见:http://nginx.org/en/docs/http/ngx_http_upstream_module.html
144 | server 10.10.11.1:80;
145 | server 10.10.11.2:80;
146 | server 10.10.11.3:80 backup;
147 | }
148 |
149 | server {
150 | # 默认服务器
151 | listen 80 default_server;
152 | listen [::]:80 default_server;
153 |
154 | # 指定端口
155 | # listen 80;
156 | # listen [::]:80;
157 | # server_name example.tld;
158 |
159 | location / {
160 | return 301 https://$host$request_uri;
161 | }
162 | }
163 |
164 | server {
165 | # 默认服务器
166 | listen 443 ssl http2 default_server;
167 | listen [::]:443 ssl http2 default_server;
168 |
169 | # 指定端口
170 | # listen 443 ssl http2;
171 | # listen [::]:443 ssl http2;
172 | # server_name example.tld;
173 |
174 | # 密钥
175 | ssl_certificate /path/to/fullchain.pem;
176 | ssl_certificate_key /path/to/private.pem;
177 | ssl_trusted_certificate /path/to/chain.pem;
178 |
179 | # 通过 https://ssl-config.mozilla.org/ 生成最佳配置
180 | ssl_session_timeout 1d;
181 | ssl_session_cache shared:FastifyApp:10m;
182 | ssl_session_tickets off;
183 |
184 | # 现代化配置
185 | ssl_protocols TLSv1.3;
186 | ssl_prefer_server_ciphers off;
187 |
188 | # HTTP 严格传输安全 (HSTS) (需要 ngx_http_headers_module 模块) (63072000 秒)
189 | add_header Strict-Transport-Security "max-age=63072000" always;
190 |
191 | # 在线证书状态协议缓存 (OCSP stapling)
192 | ssl_stapling on;
193 | ssl_stapling_verify on;
194 |
195 | # 自定义域名解析器 (resolver)
196 | # resolver 127.0.0.1;
197 |
198 | location / {
199 | # 更多信息请见:http://nginx.org/en/docs/http/ngx_http_proxy_module.html
200 | proxy_http_version 1.1;
201 | proxy_cache_bypass $http_upgrade;
202 | proxy_set_header Upgrade $http_upgrade;
203 | proxy_set_header Connection 'upgrade';
204 | proxy_set_header Host $host;
205 | proxy_set_header X-Real-IP $remote_addr;
206 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
207 | proxy_set_header X-Forwarded-Proto $scheme;
208 |
209 | proxy_pass http://fastify_app:3000;
210 | }
211 | }
212 | ```
213 |
214 | [nginx]: https://nginx.org/
215 |
216 | ## Kubernetes
217 |
218 |
219 | `readinessProbe` ([默认情况下](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#configure-probes)) 使用 pod 的 IP 作为主机名。而 Fastify 默认监听的是 `127.0.0.1`。在这种情况下,探针 (probe) 无法探测到应用。这时,应用必须监听 `0.0.0.0`,或在 `readinessProbe.httpGet` 中如下指定一个主机名,才能正常工作:
220 |
221 | ```yaml
222 | readinessProbe:
223 | httpGet:
224 | path: /health
225 | port: 4000
226 | initialDelaySeconds: 30
227 | periodSeconds: 30
228 | timeoutSeconds: 3
229 | successThreshold: 1
230 | failureThreshold: 5
--------------------------------------------------------------------------------
/docs/Reply.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 回复
4 | - [回复](#reply)
5 | - [简介](#introduction)
6 | - [.code(statusCode)](#codestatuscode)
7 | - [.statusCode](#statusCode)
8 | - [.server](#server)
9 | - [.header(key, value)](#headerkey-value)
10 | - [.getHeader(key)](#getheaderkey)
11 | - [.removeHeader(key)](#removeheaderkey)
12 | - [.hasHeader(key)](#hasheaderkey)
13 | - [.redirect([code,] dest)](#redirectcode--dest)
14 | - [.callNotFound()](#callnotfound)
15 | - [.getResponseTime()](#getresponsetime)
16 | - [.type(contentType)](#typecontenttype)
17 | - [.raw](#raw)
18 | - [.serializer(func)](#serializerfunc)
19 | - [.sent](#sent)
20 | - [.hijack](#hijack)
21 | - [.send(data)](#senddata)
22 | - [对象](#objects)
23 | - [字符串](#strings)
24 | - [Streams](#streams)
25 | - [Buffers](#buffers)
26 | - [Errors](#errors)
27 | - [最终 payload 的类型](#type-of-the-final-payload)
28 | - [Async-Await 与 Promise](#async-await-and-promises)
29 | - [.then](#then)
30 |
31 |
32 | ### 简介
33 | 处理函数的第二个参数为 `Reply`。
34 | Reply 是 Fastify 的一个核心对象。它暴露了以下函数及属性:
35 |
36 | - `.code(statusCode)` - 设置状态码。
37 | - `.status(statusCode)` - `.code(statusCode)` 的别名。
38 | - `.server` - Fastify 实例的引用。
39 | - `.statusCode` - 获取或设置 HTTP 状态码。
40 | - `.header(name, value)` - 设置响应 header。
41 | - `.getHeader(name)` - 获取某个 header 的值。
42 | - `.removeHeader(key)` - 清除已设置的 header 的值。
43 | - `.hasHeader(name)` - 检查某个 header 是否设置。
44 | - `.type(value)` - 设置 `Content-Type` header。
45 | - `.redirect([code,] dest)` - 重定向至指定的 url,状态码可选 (默认为 `302`)。
46 | - `.callNotFound()` - 调用自定义的 not found 处理函数。
47 | - `.serialize(payload)` - 使用默认的或自定义的 JSON 序列化工具序列化指定的 payload,并返回处理后的结果。
48 | - `.serializer(function)` - 设置自定义的 payload 序列化工具。
49 | - `.send(payload)` - 向用户发送 payload。类型可以是纯文本、buffer、JSON、stream,或一个 Error 对象。
50 | - `.sent` - 一个 boolean,检查 `send` 是否已被调用。
51 | - `.raw` - Node 原生的 [`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse) 对象。
52 | - `.res` *(不推荐,请使用 `.raw`)* - Node 原生的 [`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse) 对象。
53 | - `.log` - 请求的日志实例。
54 | - `.request` - 请求。
55 | - `.context` - [请求的 context](Request.md#Request) 属性。
56 |
57 | ```js
58 | fastify.get('/', options, function (request, reply) {
59 | // 你的代码
60 | reply
61 | .code(200)
62 | .header('Content-Type', 'application/json; charset=utf-8')
63 | .send({ hello: 'world' })
64 | })
65 | ```
66 |
67 | 另外,`Reply` 能够访问请求的上下文:
68 |
69 | ```js
70 | fastify.get('/', {config: {foo: 'bar'}}, function (request, reply) {
71 | reply.send('handler config.foo = ' + reply.context.config.foo)
72 | })
73 | ```
74 |
75 |
76 | ### .code(statusCode)
77 | 如果没有设置 `reply.code`,`statusCode` 会是 `200`。
78 |
79 |
80 | ### .statusCode
81 | 获取或设置 HTTP 状态码。作为 setter 使用时,是 `reply.code()` 的别名。
82 | ```js
83 | if (reply.statusCode >= 299) {
84 | reply.statusCode = 500
85 | }
86 | ```
87 |
88 |
89 | ### .server
90 | Fastify 服务器的实例,以当前的[封装上下文](Encapsulation.md)为作用域。
91 |
92 | ```js
93 | fastify.decorate('util', function util () {
94 | return 'foo'
95 | })
96 | fastify.get('/', async function (req, rep) {
97 | return rep.server.util() // foo
98 | })
99 | ```
100 |
101 |
102 | ### .header(key, value)
103 | 设置响应 header。如果值被省略或为 undefined,将被强制设成 `''`。
104 |
105 | 更多信息,请看 [`http.ServerResponse#setHeader`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_response_setheader_name_value)。
106 |
107 |
108 | ### .getHeader(key)
109 | 获取已设置的 header 的值。
110 | ```js
111 | reply.header('x-foo', 'foo') // 设置 x-foo header 的值为 foo
112 | reply.getHeader('x-foo') // 'foo'
113 | ```
114 |
115 |
116 | ### .removeHeader(key)
117 |
118 | 清除已设置的 header 的值。
119 | ```js
120 | reply.header('x-foo', 'foo')
121 | reply.removeHeader('x-foo')
122 | reply.getHeader('x-foo') // undefined
123 | ```
124 |
125 |
126 | ### .hasHeader(key)
127 | 返回一个 boolean,用于检查是否设置了某个 header。
128 |
129 |
130 | ### .redirect([code ,] dest)
131 | 重定向请求至指定的 URL,状态码可选,当未通过 `code` 方法设置时,默认为 `302`。
132 |
133 | 示例 (不调用 `reply.code()`):状态码 `302`,重定向至 `/home`
134 | ```js
135 | reply.redirect('/home')
136 | ```
137 |
138 | 示例 (不调用 `reply.code()`):状态码 `303`,重定向至 `/home`
139 | ```js
140 | reply.redirect(303, '/home')
141 | ```
142 |
143 | 示例 (调用 `reply.code()`):状态码 `303`,重定向至 `/home`
144 | ```js
145 | reply.code(303).redirect('/home')
146 | ```
147 |
148 | 示例 (调用 `reply.code()`):状态码 `302`,重定向至 `/home`
149 | ```js
150 | reply.code(303).redirect(302, '/home')
151 | ```
152 |
153 |
154 | ### .callNotFound()
155 | 调用自定义的 not found 处理函数。注意,只有在 [`setNotFoundHandler`](Server.md#set-not-found-handler) 中指明的 `preHandler` 钩子会被调用。
156 |
157 | ```js
158 | reply.callNotFound()
159 | ```
160 |
161 |
162 | ### .getResponseTime()
163 | 调用自定义响应时间获取函数,来计算自收到请求起的时间。
164 |
165 | ```js
166 | const milliseconds = reply.getResponseTime()
167 | ```
168 |
169 |
170 | ### .type(contentType, type)
171 | 设置响应的 content type。
172 | 这是 `reply.header('Content-Type', 'the/type')` 的简写。
173 |
174 | ```js
175 | reply.type('text/html')
176 | ```
177 | 如果 `Content-Type` 为 JSON 子类型,并且未设置 charset 参数,则使用 `utf-8` 作为 charset 的默认参数。
178 |
179 |
180 | ### .serializer(func)
181 | `.send()` 方法会默认将 `Buffer`、`stream`、`string`、`undefined`、`Error` 之外类型的值 JSON-序列化。假如你需要在特定的请求上使用自定义的序列化工具,你可以通过 `.serializer()` 来实现。要注意的是,如果使用了自定义的序列化工具,你必须同时设置 `'Content-Type'` header。
182 |
183 | ```js
184 | reply
185 | .header('Content-Type', 'application/x-protobuf')
186 | .serializer(protoBuf.serialize)
187 | ```
188 |
189 | 注意,你并不需要在一个 `handler` 内部使用这一工具,因为 Buffers、streams 以及字符串 (除非已经设置了序列化工具) 被认为是已序列化过的。
190 |
191 | ```js
192 | reply
193 | .header('Content-Type', 'application/x-protobuf')
194 | .send(protoBuf.serialize(data))
195 | ```
196 |
197 | 请看 [`.send()`](#send) 了解更多关于发送不同类型值的信息。
198 |
199 |
200 | ### .raw
201 | Node 核心的 [`http.ServerResponse`](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_class_http_serverresponse) 对象。使用 `Reply.raw` 上的方法会跳过 Fastify 对 HTTP 响应的处理逻辑,所以请谨慎使用。以下是一个例子:
202 |
203 | ```js
204 | app.get('/cookie-2', (req, reply) => {
205 | reply.setCookie('session', 'value', { secure: false }) // 这行不会应用
206 |
207 | // 在这个例子里我们只使用了 nodejs 的 http 响应对象
208 | reply.raw.writeHead(200, { 'Content-Type': 'text/plain' })
209 | reply.raw.write('ok')
210 | reply.raw.end()
211 | })
212 | ```
213 | 在《[回复](Reply.md#getheaders)》里有另一个误用 `Reply.raw` 的例子。
214 |
215 |
216 | ### .sent
217 |
218 | 如你所见,`.sent` 属性表明是否已通过 `reply.send()` 发送了一个响应。
219 |
220 | 当控制器是一个 async 函数或返回一个 promise 时,可以手动设置 `reply.sent = true`,以防 promise resolve 时自动调用 `reply.send()`。通过设置 `reply.sent =
221 | true`,程序能完全掌控底层的请求,且相关钩子不会被触发。
222 |
223 | 请看范例:
224 |
225 | ```js
226 | app.get('/', (req, reply) => {
227 | reply.sent = true
228 | reply.raw.end('hello world')
229 |
230 | return Promise.resolve('this will be skipped') // 译注:该处会被跳过
231 | })
232 | ```
233 |
234 | 如果处理函数 reject,将会记录一个错误。
235 |
236 |
237 | ### .hijack()
238 | 有时你需要终止请求生命周期的执行,并手动发送响应。
239 |
240 | Fastify 提供了 `reply.hijack()` 方法来完成此任务。在 `reply.send()` 之前的任意节点调用该方法,能阻止 Fastify 自动发送响应,并不再执行之后的生命周期函数 (包括用户编写的处理函数)。
241 |
242 | 特别注意 (*):假如使用了 `reply.raw` 来发送响应,则 `onResponse` 依旧会执行。
243 |
244 |
245 | ### .send(data)
246 | 顾名思义,`.send()` 是向用户发送 payload 的函数。
247 |
248 |
249 | #### 对象
250 | 如上文所述,如果你发送 JSON 对象时,设置了输出的 schema,那么 `send` 会使用 [fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) 来序列化对象。否则,将使用 `JSON.stringify()`。
251 | ```js
252 | fastify.get('/json', options, function (request, reply) {
253 | reply.send({ hello: 'world' })
254 | })
255 | ```
256 |
257 |
258 | #### 字符串
259 | 在未设置 `Content-Type` 的时候,字符串会以 `text/plain; charset=utf-8` 类型发送。如果设置了 `Content-Type`,且使用自定义序列化工具,那么 `send` 发出的字符串会被序列化。否则,字符串不会有任何改动 (除非 `Content-Type` 的值为 `application/json; charset=utf-8`,这时,字符串会像对象一样被 JSON-序列化,正如上一节所述)。
260 | ```js
261 | fastify.get('/json', options, function (request, reply) {
262 | reply.send('plain string')
263 | })
264 | ```
265 |
266 |
267 | #### Streams
268 | *send* 开箱即用地支持 stream。如果在未设置 `'Content-Type'` header 的情况下发送 stream,它会被设定为 `'application/octet-stream'`。
269 | ```js
270 | fastify.get('/streams', function (request, reply) {
271 | const fs = require('fs')
272 | const stream = fs.createReadStream('some-file', 'utf8')
273 | reply.send(stream)
274 | })
275 | ```
276 |
277 |
278 | #### Buffers
279 | 未设置 `'Content-Type'` header 的情况下发送 buffer,*send* 会将其设置为 `'application/octet-stream'`。
280 | ```js
281 | const fs = require('fs')
282 | fastify.get('/streams', function (request, reply) {
283 | fs.readFile('some-file', (err, fileBuffer) => {
284 | reply.send(err || fileBuffer)
285 | })
286 | })
287 | ```
288 |
289 |
290 | #### Errors
291 | 若使用 *send* 发送一个 *Error* 的实例,Fastify 会自动创建一个如下的错误结构:
292 |
293 | ```js
294 | {
295 | error: String // HTTP 错误信息
296 | code: String // Fastify 的错误代码
297 | message: String // 用户错误信息
298 | statusCode: Number // HTTP 状态码
299 | }
300 | ```
301 |
302 | 你可以向 Error 对象添加自定义属性,例如 `headers`,这可以用来增强 HTTP 响应。
303 | *注意:如果 `send` 一个错误,但状态码小于 400,Fastify 会自动将其设为 500。*
304 |
305 | 贴士:你可以通过 [`http-errors`](https://npm.im/http-errors) 或 [`fastify-sensible`](https://github.com/fastify/fastify-sensible) 来简化生成的错误:
306 |
307 | ```js
308 | fastify.get('/', function (request, reply) {
309 | reply.send(httpErrors.Gone())
310 | })
311 | ```
312 |
313 | 你可以通过如下方式自定义 JSON 错误的输出:
314 |
315 | - 为自定义状态码设置响应 JSON schema。
316 | - 为 `Error` 实例添加额外属性。
317 |
318 | 请注意,如果返回的状态码不在响应 schema 列表里,那么默认行为将被应用。
319 |
320 | ```js
321 | fastify.get('/', {
322 | schema: {
323 | response: {
324 | 501: {
325 | type: 'object',
326 | properties: {
327 | statusCode: { type: 'number' },
328 | code: { type: 'string' },
329 | error: { type: 'string' },
330 | message: { type: 'string' },
331 | time: { type: 'string' }
332 | }
333 | }
334 | }
335 | }
336 | }, function (request, reply) {
337 | const error = new Error('This endpoint has not been implemented')
338 | error.time = 'it will be implemented in two weeks'
339 | reply.code(501).send(error)
340 | })
341 | ```
342 |
343 | 如果你想自定义错误处理,请看 [`setErrorHandler`](Server.md#seterrorhandler) API。
344 | *注:当自定义错误处理时,你需要自行记录日志*
345 |
346 | API:
347 |
348 | ```js
349 | fastify.setErrorHandler(function (error, request, reply) {
350 | request.log.warn(error)
351 | var statusCode = error.statusCode >= 400 ? error.statusCode : 500
352 | reply
353 | .code(statusCode)
354 | .type('text/plain')
355 | .send(statusCode >= 500 ? 'Internal server error' : error.message)
356 | })
357 | ```
358 |
359 | 路由生成的 not found 错误会使用 [`setNotFoundHandler`](Server.md#setnotfoundhandler)。
360 | API:
361 |
362 | ```js
363 | fastify.setNotFoundHandler(function (request, reply) {
364 | reply
365 | .code(404)
366 | .type('text/plain')
367 | .send('a custom not found')
368 | })
369 | ```
370 |
371 |
372 | #### 最终 payload 的类型
373 | 发送的 payload (序列化之后、经过任意的 [`onSend` 钩子](Hooks.md#the-onsend-hook)) 必须为下列类型之一,否则将会抛出一个错误:
374 |
375 | - `string`
376 | - `Buffer`
377 | - `stream`
378 | - `undefined`
379 | - `null`
380 |
381 |
382 | #### Async-Await 与 Promise
383 | Fastify 原生地处理 promise 并支持 async-await。
384 | *请注意,在下面的例子中我们没有使用 reply.send。*
385 | ```js
386 | const delay = promisify(setTimeout)
387 |
388 | fastify.get('/promises', options, function (request, reply) {
389 | return delay(200).then(() => { return { hello: 'world' }})
390 | })
391 |
392 | fastify.get('/async-await', options, async function (request, reply) {
393 | await delay(200)
394 | return { hello: 'world' }
395 | })
396 | ```
397 |
398 | 被 reject 的 promise 默认发送 `500` 状态码。要修改回复,可以 reject 一个 promise,或在 `async 函数` 中进行 `throw` 操作,同时附带一个有 `statusCode` (或 `status`) 与 `message` 属性的对象。
399 |
400 | ```js
401 | fastify.get('/teapot', async function (request, reply) {
402 | const err = new Error()
403 | err.statusCode = 418
404 | err.message = 'short and stout'
405 | throw err
406 | })
407 |
408 | fastify.get('/botnet', async function (request, reply) {
409 | throw { statusCode: 418, message: 'short and stout' }
410 | // 这一 json 对象将被发送给客户端
411 | })
412 | ```
413 |
414 | 想要了解更多?请看 [Routes#async-await](Routes.md#async-await)。
415 |
416 |
417 | ### .then(fulfilled, rejected)
418 |
419 | 顾名思义,`Reply` 对象能被等待。换句话说,`await reply` 将会等待,直到回复被发送。
420 | 如上的 `await` 语法调用了 `reply.then()`。
421 |
422 | `reply.then(fulfilled, rejected)` 接受两个参数:
423 |
424 | - `fulfilled` 会在响应完全发送后被调用。
425 | - `rejected` 会在底层的 stream 出现错误时被调用。例如,socket 连接被破坏时。
426 |
427 | 更多细节,请看:
428 |
429 | - https://github.com/fastify/fastify/issues/1864,关于该特性的讨论。
430 | - https://promisesaplus.com/,thenable 的定义。
431 | - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then,`then` 的使用。
432 |
--------------------------------------------------------------------------------
/docs/Request.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## Request
4 | 处理函数的第一个参数是 `Request`.
5 | Request 是 Fastify 的核心对象,包含了以下字段:
6 | - `query` - 解析后的 querystring,其格式由 [`querystringParser`](Server.md#querystringParser) 指定。
7 | - `body` - 消息主体
8 | - `params` - URL 参数
9 | - [`headers`](#headers) - header 的 getter 与 setter
10 | - `raw` - Node 原生的 HTTP 请求
11 | - `req` *(不推荐,请使用 `.raw`)* - Node 原生的 HTTP 请求
12 | - `server` - Fastify 服务器的实例,以当前的[封装上下文](Encapsulation.md)为作用域。
13 | - `id` - 请求 ID
14 | - `log` - 请求的日志实例
15 | - `ip` - 请求方的 ip 地址
16 | - `ips` - x-forwarder-for header 中保存的请求源 ip 数组,按访问先后排序 (仅当 [`trustProxy`](Server.md#factory-trust-proxy) 开启时有效)
17 | - `hostname` - 请求方的主机名 (当 [`trustProxy`](Server.md#factory-trust-proxy) 启用时,从 `X-Forwarded-Host` header 中获取)。为了兼容 HTTP/2,当没有相关 header 存在时,将返回 `:authority`。
18 | - `protocol` - 请求协议 (`https` 或 `http`)
19 | - `method` - 请求方法
20 | - `url` - 请求路径
21 | - `routerMethod` - 处理请求的路由函数
22 | - `routerPath` - 处理请求的路由的匹配模式
23 | - `is404` - 当请求被 404 处理时为 true,反之为 false
24 | - `connection` - 不推荐,请使用 `socket`。请求的底层连接
25 | - `socket` - 请求的底层连接
26 | - `context` - Fastify 内建的对象。你不应该直接使用或修改它,但可以访问它的下列特殊属性:
27 | - `context.config` - 路由的 [`config`](Routes.md#routes-config) 对象。
28 |
29 | ### Headers
30 |
31 | `request.headers` 返回来访请求的 header 对象。你也可以如下设置自定义的 header:
32 |
33 | ```js
34 | request.headers = {
35 | 'foo': 'bar',
36 | 'baz': 'qux'
37 | }
38 | ```
39 |
40 | 该操作能向请求 header 添加新的值,且该值能通过 `request.headers.bar` 读取。此外,`request.raw.headers` 能让你访问标准的请求 header。
41 |
42 | ```js
43 | fastify.post('/:params', options, function (request, reply) {
44 | console.log(request.body)
45 | console.log(request.query)
46 | console.log(request.params)
47 | console.log(request.headers)
48 | console.log(request.raw)
49 | console.log(request.server)
50 | console.log(request.id)
51 | console.log(request.ip)
52 | console.log(request.ips)
53 | console.log(request.hostname)
54 | console.log(request.protocol)
55 | console.log(request.url)
56 | console.log(request.routerMethod)
57 | console.log(request.routerPath)
58 | request.log.info('some info')
59 | })
60 | ```
61 |
--------------------------------------------------------------------------------
/docs/Routes.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 路由
4 |
5 | 路由方法设置你程序的路由。
6 | 你可以使用简写定义与完整定义两种方式来设定路由。
7 |
8 | - [完整定义](#full-declaration)
9 | - [路由选项](#options)
10 | - [简写定义](#shorthand-declaration)
11 | - [URL 参数](#url-building)
12 | - [使用 `async`/`await`](#async-await)
13 | - [Promise 取舍](#promise-resolution)
14 | - [路由前缀](#route-prefixing)
15 | - 日志
16 | - [自定义日志级别](#custom-log-level)
17 | - [自定义日志序列化器](#custom-log-serializer)
18 | - [配置路由的处理函数](#routes-config)
19 | - [路由约束](#constraints)
20 |
21 |
22 | ### 完整定义
23 |
24 | ```js
25 | fastify.route(options)
26 | ```
27 |
28 |
29 | ### 路由选项
30 |
31 | * `method`:支持的 HTTP 请求方法。目前支持 `'DELETE'`、`'GET'`、`'HEAD'`、`'PATCH'`、`'POST'`、`'PUT'` 以及 `'OPTIONS'`。它还可以是一个 HTTP 方法的数组。
32 | * `url`:路由匹配的 URL 路径 (别名:`path`)。
33 | * `schema`:用于验证请求与回复的 schema 对象。
34 | 必须符合 [JSON Schema](https://json-schema.org/) 格式。请看[这里](Validation-and-Serialization.md)了解更多信息。
35 |
36 | * `body`:当为 POST 或 PUT 方法时,校验请求主体。
37 | * `querystring` 或 `query`:校验 querystring。可以是一个完整的 JSON Schema 对象,它包括了值为 `object` 的 `type` 属性以及包含参数的 `properties` 对象,也可以仅仅是 `properties` 对象中的值 (见下文示例)。
38 | * `params`:校验 url 参数。
39 | * `response`:过滤并生成用于响应的 schema,能帮助提升 10-20% 的吞吐量。
40 | * `exposeHeadRoute`:为任意 `GET` 路由创建一个对应的 `HEAD` 路由。默认值为服务器实例上的 [`exposeHeadRoutes`](Server.md#exposeHeadRoutes) 选项的值。如果你不想禁用该选项,又希望自定义 `HEAD` 处理函数,请在 `GET` 路由前定义该处理函数。
41 | * `attachValidation`:当 schema 校验出错时,将一个 `validationError` 对象添加到请求中,否则错误将被发送给错误处理函数。
42 | * `onRequest(request, reply, done)`:每当接收到一个请求时触发的[函数](Hooks.md#onrequest)。可以是一个函数数组。
43 | * `preParsing(request, reply, done)`:解析请求前调用的[函数](Hooks.md#preparsing)。可以是一个函数数组。
44 | * `preValidation(request, reply, done)`:在共享的 `preValidation` 钩子之后执行的[函数](Hooks.md#prevalidation),在路由层进行认证等场景中会有用处。可以是一个函数数组。
45 | * `preHandler(request, reply, done)`:处理请求之前调用的[函数](Hooks.md#prehandler)。可以是一个函数数组。
46 | * `preSerialization(request, reply, payload, done)`:序列化之前调用的[函数](Hooks.md#preserialization)。可以是一个函数数组。
47 | * `onSend(request, reply, payload, done)`:响应即将发送前调用的[函数](Hooks.md#route-hooks)。可以是一个函数数组。
48 | * `onResponse(request, reply, done)`:当响应发送后调用的[函数](Hooks.md#onresponse)。因此,在这个函数内部,不允许再向客户端发送数据。可以是一个函数数组。
49 | * `handler(request, reply)`:处理请求的函数。函数被调用时,[Fastify server](Server.md) 将会与 `this` 进行绑定。注意,使用箭头函数会破坏这一绑定。
50 | * `errorHandler(error, request, reply)`:在请求作用域内使用的自定义错误控制函数。覆盖默认的全局错误函数,以及由 [`setErrorHandler`](Server.md#setErrorHandler) 设置的请求错误函数。你可以通过 `instance.errorHandler` 访问默认的错误函数,在没有插件覆盖的情况下,其指向 Fastify 默认的 `errorHandler`。
51 | * `validatorCompiler({ schema, method, url, httpPart })`:生成校验请求的 schema 的函数。详见[验证与序列化](Validation-and-Serialization.md#schema-validator)。
52 | * `serializerCompiler({ { schema, method, url, httpStatus } })`:生成序列化响应的 schema 的函数。详见[验证与序列化](Validation-and-Serialization.md#schema-serializer)。
53 | * `schemaErrorFormatter(errors, dataVar)`:生成一个函数,用于格式化来自 schema 校验函数的错误。详见[验证与序列化](Validation-and-Serialization.md#schema-validator)。在当前路由上会覆盖全局的 schema 错误格式化函数,以及 `setSchemaErrorFormatter` 设置的值。
54 | * `bodyLimit`:一个以字节为单位的整形数,默认值为 `1048576` (1 MiB),防止默认的 JSON 解析器解析超过此大小的请求主体。你也可以通过 `fastify(options)`,在首次创建 Fastify 实例时全局设置该值。
55 | * `logLevel`:设置日志级别。详见下文。
56 | * `logSerializers`:设置当前路由的日志序列化器。
57 | * `config`:存放自定义配置的对象。
58 | * `version`:一个符合[语义化版本控制规范 (semver)](https://semver.org/) 的字符串。[示例](Routes.md#version)。
59 | `prefixTrailingSlash`:一个字符串,决定如何处理带前缀的 `/` 路由。
60 | * `both` (默认值):同时注册 `/prefix` 与 `/prefix/`。
61 | * `slash`:只会注册 `/prefix/`。
62 | * `no-slash`:只会注册 `/prefix`。
63 |
64 | `request` 的相关内容请看[请求](Request.md)一文。
65 |
66 | `reply` 请看[回复](Reply.md)一文。
67 |
68 | **注意:** 在[钩子](Hooks.md)一文中有 `onRequest`、`preParsing`、`preValidation`、`preHandler`、`preSerialization`、`onSend` 以及 `onResponse` 更详尽的说明。此外,要在 `handler` 之前就发送响应,请参阅[在钩子中响应请求](Hooks.md#respond-to-a-request-from-a-hook)。
69 |
70 | 示例:
71 | ```js
72 | fastify.route({
73 | method: 'GET',
74 | url: '/',
75 | schema: {
76 | querystring: {
77 | name: { type: 'string' },
78 | excitement: { type: 'integer' }
79 | },
80 | response: {
81 | 200: {
82 | type: 'object',
83 | properties: {
84 | hello: { type: 'string' }
85 | }
86 | }
87 | }
88 | },
89 | handler: function (request, reply) {
90 | reply.send({ hello: 'world' })
91 | }
92 | })
93 | ```
94 |
95 |
96 | ### 简写定义
97 | 上文的路由定义带有 *Hapi* 的风格。要是偏好 *Express/Restify* 的写法,Fastify 也是支持的:
98 | `fastify.get(path, [options], handler)`
99 | `fastify.head(path, [options], handler)`
100 | `fastify.post(path, [options], handler)`
101 | `fastify.put(path, [options], handler)`
102 | `fastify.delete(path, [options], handler)`
103 | `fastify.options(path, [options], handler)`
104 | `fastify.patch(path, [options], handler)`
105 |
106 | 示例:
107 | ```js
108 | const opts = {
109 | schema: {
110 | response: {
111 | 200: {
112 | type: 'object',
113 | properties: {
114 | hello: { type: 'string' }
115 | }
116 | }
117 | }
118 | }
119 | }
120 | fastify.get('/', opts, (request, reply) => {
121 | reply.send({ hello: 'world' })
122 | })
123 | ```
124 |
125 | `fastify.all(path, [options], handler)` 会给所有支持的 HTTP 方法添加相同的处理函数。
126 |
127 | 处理函数还可以写到 `options` 对象里:
128 | ```js
129 | const opts = {
130 | schema: {
131 | response: {
132 | 200: {
133 | type: 'object',
134 | properties: {
135 | hello: { type: 'string' }
136 | }
137 | }
138 | }
139 | },
140 | handler: function (request, reply) {
141 | reply.send({ hello: 'world' })
142 | }
143 | }
144 | fastify.get('/', opts)
145 | ```
146 |
147 | > 注:假如同时在 `options` 和简写方法的第三个参数里指明了处理函数,将会抛出重复的 `handler` 错误。
148 |
149 |
150 | ### Url 构建
151 | Fastify 同时支持静态与动态的 URL
152 | 要注册一个**参数命名**的路径,请在参数名前加上*冒号*。*星号*表示**通配符**。
153 | *注意,静态路由总是在参数路由和通配符之前进行匹配。*
154 |
155 | ```js
156 | // 参数路由
157 | fastify.get('/example/:userId', (request, reply) => {})
158 | fastify.get('/example/:userId/:secretToken', (request, reply) => {})
159 |
160 | // 通配符
161 | fastify.get('/example/*', (request, reply) => {})
162 | ```
163 |
164 | 正则表达式路由亦被支持。但要注意,正则表达式会严重拖累性能!
165 | ```js
166 | // 正则表达的参数路由
167 | fastify.get('/example/:file(^\\d+).png', (request, reply) => {})
168 | ```
169 |
170 | 你还可以在同一组斜杠 ("/") 里定义多个参数。就像这样:
171 | ```js
172 | fastify.get('/example/near/:lat-:lng/radius/:r', (request, reply) => {})
173 | ```
174 | *使用短横线 ("-") 来分隔参数。*
175 |
176 | 最后,同时使用多参数和正则表达式也是允许的。
177 | ```js
178 | fastify.get('/example/at/:hour(^\\d{2})h:minute(^\\d{2})m', (request, reply) => {})
179 | ```
180 | 在这个例子里,任何未被正则匹配的符号均可作为参数的分隔符。
181 |
182 | 多参数的路由会影响性能,所以应该尽量使用单参数,对于高频访问的路由来说更是如此。
183 | 如果你对路由的底层感兴趣,可以查看[find-my-way](https://github.com/delvedor/find-my-way)。
184 |
185 | 双冒号表示字面意义上的一个冒号,这样就不必通过参数来实现带冒号的路由了。举例如下:
186 | ```js
187 | fastify.post('/name::verb') // 将被解释为 /name:verb
188 | ```
189 |
190 |
191 | ### Async Await
192 | 你是 `async/await` 的使用者吗?我们为你考虑了一切!
193 | ```js
194 | fastify.get('/', options, async function (request, reply) {
195 | var data = await getData()
196 | var processed = await processData(data)
197 | return processed
198 | })
199 | ```
200 |
201 | 如你所见,我们不再使用 `reply.send` 向用户发送数据,只需返回消息主体就可以了!
202 |
203 | 当然,需要的话你还是可以使用 `reply.send` 发送数据。
204 | ```js
205 | fastify.get('/', options, async function (request, reply) {
206 | var data = await getData()
207 | var processed = await processData(data)
208 | reply.send(processed)
209 | })
210 | ```
211 |
212 | 假如在路由中,`reply.send()` 脱离了 promise 链,在一个基于回调的 API 中被调用,你可以使用 `await reply`:
213 |
214 | ```js
215 | fastify.get('/', options, async function (request, reply) {
216 | setImmediate(() => {
217 | reply.send({ hello: 'world' })
218 | })
219 | await reply
220 | })
221 | ```
222 |
223 | 返回回复也是可行的:
224 |
225 | ```js
226 | fastify.get('/', options, async function (request, reply) {
227 | setImmediate(() => {
228 | reply.send({ hello: 'world' })
229 | })
230 | return reply
231 | })
232 | ```
233 |
234 | **警告:**
235 | * 如果你同时使用 `return value` 与 `reply.send(value)`,那么只会发送第一次,同时还会触发警告日志,因为你试图发送两次响应。
236 | * 不能返回 `undefined`。更多细节请看 [promise 取舍](#promise-resolution)。
237 |
238 |
239 | ### Promise 取舍
240 |
241 | 假如你的处理函数是一个 `async` 函数,或返回了一个 promise,请注意一种必须支持回调函数和 promise 控制流的特殊情况:如果 promise 被 resolve 为 `undefined`,请求会被挂起,并触发一个*错误*日志。
242 |
243 | 1. 如果你想使用 `async/await` 或 promise,但通过 `reply.send` 返回值:
244 | - **别** `return` 任何值。
245 | - **别**忘了 `reply.send`。
246 | 2. 如果你想使用 `async/await` 或 promise:
247 | - **别**使用 `reply.send`。
248 | - **别**返回 `undefined`。
249 |
250 | 通过这一方法,我们便可以最小代价同时支持 `回调函数风格` 以及 `async-await`。尽管这么做十分自由,我们还是强烈建议仅使用其中的一种,因为应用的错误处理方式应当保持一致。
251 |
252 | **注意**:每个 async 函数各自返回一个 promise 对象。
253 |
254 |
255 | ### 路由前缀
256 | 有时你需要维护同一 API 的多个不同版本。一般的做法是在所有的路由之前加上版本号,例如 `/v1/user`。
257 | Fastify 提供了一个快捷且智能的方法来解决上述问题,无需手动更改全部路由。这就是*路由前缀*。让我们来看下吧:
258 |
259 | ```js
260 | // server.js
261 | const fastify = require('fastify')()
262 |
263 | fastify.register(require('./routes/v1/users'), { prefix: '/v1' })
264 | fastify.register(require('./routes/v2/users'), { prefix: '/v2' })
265 |
266 | fastify.listen(3000)
267 | ```
268 |
269 | ```js
270 | // routes/v1/users.js
271 | module.exports = function (fastify, opts, done) {
272 | fastify.get('/user', handler_v1)
273 | done()
274 | }
275 | ```
276 |
277 | ```js
278 | // routes/v2/users.js
279 | module.exports = function (fastify, opts, done) {
280 | fastify.get('/user', handler_v2)
281 | done()
282 | }
283 | ```
284 | 在编译时 Fastify 自动处理了前缀,因此两个不同路由使用相同的路径名并不会产生问题。*(这也意味着性能一点儿也不受影响!)*。
285 |
286 | 现在,你的客户端就可以访问下列路由了:
287 | - `/v1/user`
288 | - `/v2/user`
289 |
290 | 根据需要,你可以多次设置路由前缀,它也支持嵌套的 `register` 以及路由参数。
291 | 请注意,当使用了 [`fastify-plugin`](https://github.com/fastify/fastify-plugin) 时,这一选项是无效的。
292 |
293 | #### 处理带前缀的 / 路由
294 |
295 | 根据前缀是否以 `/` 结束,路径为 `/` 的路由的匹配模式有所不同。举例来说,前缀为 `/something/` 的 `/` 路由只会匹配 `something`,而前缀为 `/something` 则会匹配 `/something` 和 `/something/`。
296 |
297 | 要改变这一行为,请见上文 `prefixTrailingSlash` 选项。
298 |
299 |
300 | ### 自定义日志级别
301 | 在 Fastify 中为路由里设置不同的日志级别是十分容易的。
302 | 你只需在插件或路由的选项里设置 `logLevel` 为相应的[值](https://github.com/pinojs/pino/blob/master/docs/api.md#level-string)即可。
303 |
304 | 要注意的是,如果在插件层面上设置了 `logLevel`,那么 [`setNotFoundHandler`](Server.md#setnotfoundhandler) 和 [`setErrorHandler`](Server.md#seterrorhandler) 也会受到影响。
305 |
306 | ```js
307 | // server.js
308 | const fastify = require('fastify')({ logger: true })
309 |
310 | fastify.register(require('./routes/user'), { logLevel: 'warn' })
311 | fastify.register(require('./routes/events'), { logLevel: 'debug' })
312 |
313 | fastify.listen(3000)
314 | ```
315 |
316 | 你也可以直接将其传给路由:
317 | ```js
318 | fastify.get('/', { logLevel: 'warn' }, (request, reply) => {
319 | reply.send({ hello: 'world' })
320 | })
321 | ```
322 | *自定义的日志级别仅对路由生效,通过 `fastify.log` 访问的全局日志并不会受到影响。*
323 |
324 |
325 | ### 自定义日志序列化器
326 |
327 | 在某些上下文里,你也许需要记录一个大型对象,但这在其他路由中是个负担。这时,你可以定义一些[`序列化器 (serializer)`](https://github.com/pinojs/pino/blob/master/docs/api.md#bindingsserializers-object),并将它们设置在正确的上下文之上!
328 |
329 | ```js
330 | const fastify = require('fastify')({ logger: true })
331 | fastify.register(require('./routes/user'), {
332 | logSerializers: {
333 | user: (value) => `My serializer one - ${value.name}`
334 | }
335 | })
336 | fastify.register(require('./routes/events'), {
337 | logSerializers: {
338 | user: (value) => `My serializer two - ${value.name} ${value.surname}`
339 | }
340 | })
341 | fastify.listen(3000)
342 | ```
343 |
344 | 你可以通过上下文来继承序列化器:
345 |
346 | ```js
347 | const fastify = Fastify({
348 | logger: {
349 | level: 'info',
350 | serializers: {
351 | user (req) {
352 | return {
353 | method: req.method,
354 | url: req.url,
355 | headers: req.headers,
356 | hostname: req.hostname,
357 | remoteAddress: req.ip,
358 | remotePort: req.socket.remotePort
359 | }
360 | }
361 | }
362 | }
363 | })
364 | fastify.register(context1, {
365 | logSerializers: {
366 | user: value => `My serializer father - ${value}`
367 | }
368 | })
369 | async function context1 (fastify, opts) {
370 | fastify.get('/', (req, reply) => {
371 | req.log.info({ user: 'call father serializer', key: 'another key' })
372 | // 打印结果: { user: 'My serializer father - call father serializer', key: 'another key' }
373 | reply.send({})
374 | })
375 | }
376 | fastify.listen(3000)
377 | ```
378 |
379 |
380 | ### 配置
381 | 注册一个新的处理函数,你可以向其传递一个配置对象,并在其中使用它。
382 |
383 | ```js
384 | // server.js
385 | const fastify = require('fastify')()
386 |
387 | function handler (req, reply) {
388 | reply.send(reply.context.config.output)
389 | }
390 |
391 | fastify.get('/en', { config: { output: 'hello world!' } }, handler)
392 | fastify.get('/it', { config: { output: 'ciao mondo!' } }, handler)
393 |
394 | fastify.listen(3000)
395 | ```
396 |
397 |
398 | ### 约束
399 |
400 | Fastify 允许你基于请求的某些属性,例如 `Host` header 或 [`find-my-way`](https://github.com/delvedor/find-my-way) 指定的其他值,来限制路由仅匹配特定的请求。路由选项里的 `constraints` 属性便是用于这一特性。Fastify 有两个内建的约束属性:`version` 及 `host`。你可以自定义约束策略,来判断某路由是否处理一个请求。
401 |
402 | #### 版本约束
403 |
404 | 你可以在路由的 `constraints` 选项中提供一个 `version` 键。路由版本化允许你为相同路径的路由设置多个处理函数,并根据请求的 `Accept-Version` header 来做匹配。 `Accept-Version` header 的值请遵循 [semver](https://semver.org/) 规范,路由也应当附带对应的 semver 版本声明以便成功匹配。
405 | 对于版本化的路由,Fastify 需要请求附带上 `Accept-Version` header。此外,相同路径的请求会优先匹配带有版本的控制函数。当前尚不支持 semver 规范中的 advanced ranges 与 pre-releases 语法
406 | *请注意,这一特性会降低路由的性能。*
407 |
408 | ```js
409 | fastify.route({
410 | method: 'GET',
411 | url: '/',
412 | constraints: { version: '1.2.0' },
413 | handler: function (request, reply) {
414 | reply.send({ hello: 'world' })
415 | }
416 | })
417 |
418 | fastify.inject({
419 | method: 'GET',
420 | url: '/',
421 | headers: {
422 | 'Accept-Version': '1.x' // 也可以是 '1.2.0' 或 '1.2.x'
423 | }
424 | }, (err, res) => {
425 | // { hello: 'world' }
426 | })
427 | ```
428 |
429 | > ## ⚠ 安全提示
430 | > 记得设置 [`Vary`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary) 响应头
431 | > 为用于区分版本的值 (如 `'Accept-Version'`),
432 | > 来避免缓存污染攻击 (cache poisoning attacks)。你也可以在代理或 CDN 层设置该值。
433 | >
434 | > ```js
435 | > const append = require('vary').append
436 | > fastify.addHook('onSend', async (req, reply) => {
437 | > if (req.headers['accept-version']) { // 或其他自定义 header
438 | > let value = reply.getHeader('Vary') || ''
439 | > const header = Array.isArray(value) ? value.join(', ') : String(value)
440 | > if ((value = append(header, 'Accept-Version'))) { // 或其他自定义 header
441 | > reply.header('Vary', value)
442 | > }
443 | > }
444 | > })
445 | > ```
446 |
447 | 如果你声明了多个拥有相同主版本或次版本号的版本,Fastify 总是会根据 `Accept-Version` header 的值选择最兼容的版本。
448 | 假如请求未带有 `Accept-Version` header,那么将返回一个 404 错误。
449 |
450 | 新建 Fastify 实例时,可以通过设置 [`constraints`](Server.md#constraints) 选项,来自定义版本匹配的逻辑。
451 |
452 | #### Host 约束
453 |
454 | 你可以在路由的 `constraints` 选项中提供一个 `host` 键,使得该路由根据请求的 `Host` header 来做匹配。 `host` 约束的值可以是精确匹配的字符串,也可以是任意匹配的正则表达式
455 |
456 | ```js
457 | fastify.route({
458 | method: 'GET',
459 | url: '/',
460 | constraints: { host: 'auth.fastify.io' },
461 | handler: function (request, reply) {
462 | reply.send('hello world from auth.fastify.io')
463 | }
464 | })
465 |
466 | fastify.inject({
467 | method: 'GET',
468 | url: '/',
469 | headers: {
470 | 'Host': 'example.com'
471 | }
472 | }, (err, res) => {
473 | // 返回 404,因为 host 不匹配
474 | })
475 |
476 | fastify.inject({
477 | method: 'GET',
478 | url: '/',
479 | headers: {
480 | 'Host': 'auth.fastify.io'
481 | }
482 | }, (err, res) => {
483 | // => 'hello world from auth.fastify.io'
484 | })
485 | ```
486 |
487 | 正则形式的 `host` 约束也可用于匹配任意的子域 (或其他模式):
488 |
489 | ```js
490 | fastify.route({
491 | method: 'GET',
492 | url: '/',
493 | constraints: { host: /.*\.fastify\.io/ }, // 匹配 fastify.io 的任意子域
494 | handler: function (request, reply) {
495 | reply.send('hello world from ' + request.headers.host)
496 | }
497 | })
498 | ```
--------------------------------------------------------------------------------
/docs/Serverless.md:
--------------------------------------------------------------------------------
1 | Serverless
2 |
3 | 使用现有的 Fastify 应用运行无服务器 (serverless) 应用与 REST API。
4 |
5 | Fastify 无法直接运行在无服务器平台上,需要做一点修改。本文为如何在知名的无服务器平台上运行 Fastify 应用提供指导。
6 |
7 | #### 我应该在无服务器平台上使用 Fastify 吗?
8 |
9 | 取决于你自己!FaaS 通常使用精简专注的函数,但你依然可以运行完整的 web 应用。但请牢记,应用越繁重,初始化越漫长。在无服务器环境中运行 Fastify,最好的方式便是使用例如 Google Cloud Run、AWS Fargate 以及 Azure Container Instances 之类的平台,它们能同时处理多个请求,因此能充分利用 Fastify 的特性。
10 |
11 | 开发便利是通过 Fastify 构建无服务器应用的优势之一。在本地环境,Fastify 应用无需任何额外工具即可运作,而相同的代码加上一些额外内容便能在无服务器平台上运行。
12 |
13 | ### 目录
14 |
15 | - [AWS Lambda](#aws-lambda)
16 | - [Google Cloud Run](#google-cloud-run)
17 | - [Netlify Lambda](#netlify-lambda)
18 | - [Vercel](#vercel)
19 |
20 | ## AWS Lambda
21 |
22 | 以下是使用 Fastify 在 AWS Lambda 和 Amazon API Gateway 架构上构建无服务器 web 应用/服务的示例。
23 |
24 | *注:使用 [aws-lambda-fastify](https://github.com/fastify/aws-lambda-fastify) 仅是一种可行方案。*
25 |
26 | ### app.js
27 |
28 | ```js
29 | const fastify = require('fastify');
30 |
31 | function init() {
32 | const app = fastify();
33 | app.get('/', (request, reply) => reply.send({ hello: 'world' }));
34 | return app;
35 | }
36 |
37 | if (require.main === module) {
38 | // 直接调用,即执行 "node app"
39 | init().listen(3000, (err) => {
40 | if (err) console.error(err);
41 | console.log('server listening on 3000');
42 | });
43 | } else {
44 | // 作为模块引入 => 用于 aws lambda
45 | module.exports = init;
46 | }
47 | ```
48 |
49 | 你可以简单地把初始化代码包裹于可选的 [serverFactory](https://www.fastify.io/docs/latest/Server/#serverfactory) 选项里。
50 |
51 | 当执行 lambda 函数时,我们不需要监听特定的端口,因此,在这个例子里我们只要导出 `init` 函数即可。
52 | 在 [`lambda.js`](https://www.fastify.io/docs/latest/Serverless/#lambda-js) 里,我们会用到它。
53 |
54 | 当像往常一样运行 Fastify 应用,
55 | 比如执行 `node app.js` 时 *(可以用 `require.main === module` 来判断)*,
56 | 你可以监听某个端口,如此便能本地运行应用了。
57 |
58 | ### lambda.js
59 |
60 | ```js
61 | const awsLambdaFastify = require('aws-lambda-fastify')
62 | const init = require('./app');
63 |
64 | const proxy = awsLambdaFastify(init())
65 | // 或
66 | // const proxy = awsLambdaFastify(init(), { binaryMimeTypes: ['application/octet-stream'] })
67 |
68 | exports.handler = proxy;
69 | // 或
70 | // exports.handler = (event, context, callback) => proxy(event, context, callback);
71 | // 或
72 | // exports.handler = (event, context) => proxy(event, context);
73 | // 或
74 | // exports.handler = async (event, context) => proxy(event, context);
75 | ```
76 |
77 | 我们只需要引入 [aws-lambda-fastify](https://github.com/fastify/aws-lambda-fastify) (请确保安装了该依赖 `npm i --save aws-lambda-fastify`) 以及我们写的 [`app.js`](https://www.fastify.io/docs/latest/Serverless/#app-js),并使用 `app` 作为唯一参数调用导出的 `awsLambdaFastify` 函数。
78 | 以上步骤返回的 `proxy` 函数拥有正确的签名,可作为 lambda 的处理函数。
79 | 如此,所有的请求事件 (API Gateway 的请求) 都会被代理到 [aws-lambda-fastify](https://github.com/fastify/aws-lambda-fastify) 的 `proxy` 函数。
80 |
81 | ### 示例
82 |
83 | 你可以在[这里](https://github.com/claudiajs/example-projects/tree/master/fastify-app-lambda)找到使用 [claudia.js](https://claudiajs.com/tutorials/serverless-express.html) 的可部署的例子。
84 |
85 |
86 | ### 注意事项
87 |
88 | - 你没法操作 [stream](https://www.fastify.io/docs/latest/Reply/#streams),因为 API Gateway 还不支持它。
89 | - API Gateway 的超时时间为 29 秒,请务必在此时限内回复。
90 |
91 | ## Google Cloud Run
92 |
93 | 与 AWS Lambda 和 Google Cloud Functions 不同,Google Cloud Run 是一个无服务器**容器**环境。它的首要目的是提供一个能运行任意容器的底层抽象 (infrastucture-abstracted) 的环境。因此,你能将 Fastify 部署在 Google Cloud Run 上,而且相比正常的写法,只需要改动极少的代码。
94 |
95 | *参照以下步骤部署 Google Cloud Run。如果你对 gcloud 还不熟悉,请看其[入门文档](https://cloud.google.com/run/docs/quickstarts/build-and-deploy)*。
96 |
97 | ### 调整 Fastify 服务器
98 |
99 | 为了让 Fastify 能正确地在容器里监听请求,请确保设置了正确的端口与地址:
100 |
101 | ```js
102 | function build() {
103 | const fastify = Fastify({ trustProxy: true })
104 | return fastify
105 | }
106 |
107 | async function start() {
108 | // Google Cloud Run 会设置这一环境变量,
109 | // 因此,你可以使用它判断程序是否运行在 Cloud Run 之中
110 | const IS_GOOGLE_CLOUD_RUN = process.env.K_SERVICE !== undefined
111 |
112 | // 监听 Cloud Run 提供的端口
113 | const port = process.env.PORT || 3000
114 |
115 | // 监听 Cloud Run 中所有的 IPV4 地址
116 | const address = IS_GOOGLE_CLOUD_RUN ? "0.0.0.0" : undefined
117 |
118 | try {
119 | const server = build()
120 | const address = await server.listen(port, address)
121 | console.log(`Listening on ${address}`)
122 | } catch (err) {
123 | console.error(err)
124 | process.exit(1)
125 | }
126 | }
127 |
128 | module.exports = build
129 |
130 | if (require.main === module) {
131 | start()
132 | }
133 | ```
134 |
135 | ### 添加 Dockerfile
136 |
137 | 你可以添加任意合法的 `Dockerfile`,用于打包运行 Node 程序。在 [gcloud 官方文档](https://github.com/knative/docs/blob/2d654d1fd6311750cc57187a86253c52f273d924/docs/serving/samples/hello-world/helloworld-nodejs/Dockerfile)中,你能找到一份基本的 `Dockerfile`。
138 |
139 | ```Dockerfile
140 | # 使用官方 Node.js 10 镜像。
141 | # https://hub.docker.com/_/node
142 | FROM node:10
143 |
144 | # 创建并切换到应用目录。
145 | WORKDIR /usr/src/app
146 |
147 | # 拷贝应用依赖清单至容器镜像。
148 | # 使用通配符来确保 package.json 和 package-lock.json 均被复制。
149 | # 独立地拷贝这些文件,能防止代码改变时重复执行 npm install。
150 | COPY package*.json ./
151 |
152 | # 安装生产环境依赖。
153 | RUN npm install --only=production
154 |
155 | # 复制本地代码到容器镜像。
156 | COPY . .
157 |
158 | # 启动容器时运行服务。
159 | CMD [ "npm", "start" ]
160 | ```
161 |
162 | ### 添加 .dockerignore
163 |
164 | 添加一份如下的 `.dockerignore`,可以将仅用于构建的文件排除在容器之外 (能减小容器大小,加快构建速度):
165 |
166 | ```.dockerignore
167 | Dockerfile
168 | README.md
169 | node_modules
170 | npm-debug.log
171 | ```
172 |
173 | ### 提交构建
174 |
175 | 接下来,使用以下命令将你的应用构建成一个 Docker 镜像 (将 `PROJECT-ID` 和 `APP-NAME` 替换为 Google 云平台的项目 id 和 app 名称):
176 |
177 | ```bash
178 | gcloud builds submit --tag gcr.io/PROJECT-ID/APP-NAME
179 | ```
180 |
181 | ### 部署镜像
182 |
183 | 镜像构建之后,使用如下命令部署它:
184 |
185 | ```bash
186 | gcloud beta run deploy --image gcr.io/PROJECT-ID/APP-NAME --platform managed
187 | ```
188 |
189 | 如此,便能从 Google 云平台提供的链接访问你的应用了。
190 |
191 | ## netlify-lambda
192 |
193 | 首先,完成与 **AWS Lambda** 有关的准备工作。
194 |
195 | 新建 `functions` 文件夹,在其中创建 `server.js` (应用的入口文件)。
196 |
197 | ### functions/server.js
198 |
199 | ```js
200 | export { handler } from '../lambda.js'; // 记得将路径修改为你的应用中对应的 `lambda.js` 的路径
201 | ```
202 |
203 | ### netlify.toml
204 |
205 | ```toml
206 | [build]
207 | # 构建站点时执行的命令
208 | command = "npm run build:functions"
209 | # 发布到 netlify CDN 的文件夹
210 | # 同时也是应用的前端
211 | # publish = "build"
212 | # 构建好的 Lambda 函数的目录
213 | functions = "functions-build" # 总是为构建后的 `functions` 文件夹名称加上 `-build` 后缀
214 | ```
215 |
216 | ### webpack.config.netlify.js
217 |
218 | **别忘记添加这个文件,否则会有不少问题**
219 |
220 | ```js
221 | const nodeExternals = require('webpack-node-externals');
222 | const dotenv = require('dotenv-safe');
223 | const webpack = require('webpack');
224 |
225 | const env = process.env.NODE_ENV || 'production';
226 | const dev = env === 'development';
227 |
228 | if (dev) {
229 | dotenv.config({ allowEmptyValues: true });
230 | }
231 |
232 | module.exports = {
233 | mode: env,
234 | devtool: dev ? 'eval-source-map' : 'none',
235 | externals: [nodeExternals()],
236 | devServer: {
237 | proxy: {
238 | '/.netlify': {
239 | target: 'http://localhost:9000',
240 | pathRewrite: { '^/.netlify/functions': '' }
241 | }
242 | }
243 | },
244 | module: {
245 | rules: []
246 | },
247 | plugins: [
248 | new webpack.DefinePlugin({
249 | 'process.env.APP_ROOT_PATH': JSON.stringify('/'),
250 | 'process.env.NETLIFY_ENV': true,
251 | 'process.env.CONTEXT': env
252 | })
253 | ]
254 | };
255 | ```
256 |
257 | ### Scripts
258 |
259 | 在 `package.json` 的 *scripts* 里加上这一命令
260 |
261 | ```json
262 | "scripts": {
263 | ...
264 | "build:functions": "netlify-lambda build functions --config ./webpack.config.netlify.js"
265 | ...
266 | }
267 | ```
268 |
269 | 这样就完成了。
270 |
271 | ## Vercel
272 |
273 | [Vercel](https://vercel.com) 针对 Node.js 应用提供了零配置部署方案。要使用 now,只需要如下配置你的 `vercel.json` 文件:
274 |
275 | ```json
276 | {
277 | "rewrites": [
278 | {
279 | "source": "/(.*)",
280 | "destination": "/api/serverless.js"
281 | }
282 | ]
283 | }
284 | ```
285 |
286 | 之后,写一个 `api/serverless.js` 文件:
287 |
288 | ```js
289 | "use strict";
290 |
291 | // 读取 .env 文件
292 | import * as dotenv from "dotenv";
293 | dotenv.config();
294 |
295 | // 引入 Fastify 框架
296 | import Fastify from "fastify";
297 |
298 | // 实例化 Fastify
299 | const app = Fastify({
300 | logger: true,
301 | });
302 |
303 | // 将应用注册为一个常规插件
304 | app.register(import("../src/app"));
305 |
306 | export default async (req, res) => {
307 | await app.ready();
308 | app.server.emit('request', req, res);
309 | }
310 | ```
--------------------------------------------------------------------------------
/docs/Testing.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 测试
4 |
5 | 测试是开发应用最重要的一部分。Fastify 处理测试非常灵活并且它兼容绝大多数框架 (例如 [Tap](https://www.npmjs.com/package/tap)。下面的例子都会用这个演示)。
6 |
7 | 让我们 `cd` 进入一个全新的 'testing-example' 文件夹,并在终端里输入 `npm init -y`。
8 |
9 | 执行 `npm install fastify && npm install tap pino-pretty --save-dev`。
10 |
11 | ### 关注点分离让测试变得轻松
12 |
13 | 首先,我们将应用代码与服务器代码分离:
14 |
15 | **app.js**:
16 |
17 | ```js
18 | 'use strict'
19 |
20 | const fastify = require('fastify')
21 |
22 | function build(opts={}) {
23 | const app = fastify(opts)
24 | app.get('/', async function (request, reply) {
25 | return { hello: 'world' }
26 | })
27 |
28 | return app
29 | }
30 |
31 | module.exports = build
32 | ```
33 |
34 | **server.js**:
35 |
36 | ```js
37 | 'use strict'
38 |
39 | const server = require('./app')({
40 | logger: {
41 | level: 'info',
42 | prettyPrint: true
43 | }
44 | })
45 |
46 | server.listen(3000, (err, address) => {
47 | if (err) {
48 | console.log(err)
49 | process.exit(1)
50 | }
51 | })
52 | ```
53 |
54 | ### 使用 fastify.inject() 的好处
55 |
56 | 感谢有 [`light-my-request`](https://github.com/fastify/light-my-request),Fastify 自带了伪造的 HTTP 注入。
57 |
58 | 在进行任何测试之前,我们通过 `.inject` 方法向路由发送假的请求:
59 |
60 | **app.test.js**:
61 |
62 | ```js
63 | 'use strict'
64 |
65 | const build = require('./app')
66 |
67 | const test = async () => {
68 | const app = build()
69 |
70 | const response = await app.inject({
71 | method: 'GET',
72 | url: '/'
73 | })
74 |
75 | console.log('status code: ', response.statusCode)
76 | console.log('body: ', response.body)
77 | }
78 | test()
79 | ```
80 |
81 | 我们的代码运行在异步函数里,因此可以使用 async/await。
82 |
83 | `.inject` 确保了所有注册的插件都已引导完毕,可以开始测试应用了。之后请求方法将被传递到路由函数中去。使用 await 可以存储响应,且避免了回调函数。
84 |
85 | 在终端执行 `node app.test.js` 来开始测试。
86 |
87 | ```sh
88 | status code: 200
89 | body: {"hello":"world"}
90 | ```
91 |
92 | ### HTTP 注入测试
93 |
94 | 现在我们能用真实的测试语句代替 `console.log` 了!
95 |
96 | 在 `package.json` 里修改 "test" script 如下:
97 |
98 | `"test": "tap --reporter=list --watch"`
99 |
100 | **app.test.js**:
101 |
102 | ```js
103 | 'use strict'
104 |
105 | const { test } = require('tap')
106 | const build = require('./app')
107 |
108 | test('requests the "/" route', async t => {
109 | const app = build()
110 |
111 | const response = await app.inject({
112 | method: 'GET',
113 | url: '/'
114 | })
115 | t.equal(response.statusCode, 200, 'returns a status code of 200')
116 | })
117 | ```
118 |
119 | 执行 `npm test`,查看结果!
120 |
121 | `inject` 方法能完成的不只有简单的 GET 请求:
122 | ```js
123 | fastify.inject({
124 | method: String,
125 | url: String,
126 | query: Object,
127 | payload: Object,
128 | headers: Object,
129 | cookies: Object
130 | }, (error, response) => {
131 | // 你的测试
132 | })
133 | ```
134 |
135 | 忽略回调函数,可以链式调用 `.inject` 提供的方法:
136 |
137 | ```js
138 | fastify
139 | .inject()
140 | .get('/')
141 | .headers({ foo: 'bar' })
142 | .query({ foo: 'bar' })
143 | .end((err, res) => { // 调用 .end 触发请求
144 | console.log(res.payload)
145 | })
146 | ```
147 |
148 | 或是用 promise 的版本
149 |
150 | ```js
151 | fastify
152 | .inject({
153 | method: String,
154 | url: String,
155 | query: Object,
156 | payload: Object,
157 | headers: Object,
158 | cookies: Object
159 | })
160 | .then(response => {
161 | // 你的测试
162 | })
163 | .catch(err => {
164 | // 处理错误
165 | })
166 | ```
167 |
168 | Async await 也是支持的!
169 | ```js
170 | try {
171 | const res = await fastify.inject({ method: String, url: String, payload: Object, headers: Object })
172 | // 你的测试
173 | } catch (err) {
174 | // 处理错误
175 | }
176 | ```
177 |
178 | #### 另一个例子:
179 |
180 | **app.js**
181 | ```js
182 | const Fastify = require('fastify')
183 |
184 | function buildFastify () {
185 | const fastify = Fastify()
186 |
187 | fastify.get('/', function (request, reply) {
188 | reply.send({ hello: 'world' })
189 | })
190 |
191 | return fastify
192 | }
193 |
194 | module.exports = buildFastify
195 | ```
196 |
197 | **test.js**
198 | ```js
199 | const tap = require('tap')
200 | const buildFastify = require('./app')
201 |
202 | tap.test('GET `/` route', t => {
203 | t.plan(4)
204 |
205 | const fastify = buildFastify()
206 |
207 | // 在测试的最后,我们强烈建议你调用 `.close()`
208 | // 方法来确保所有与外部服务的连接被关闭。
209 | t.teardown(() => fastify.close())
210 |
211 | fastify.inject({
212 | method: 'GET',
213 | url: '/'
214 | }, (err, response) => {
215 | t.error(err)
216 | t.equal(response.statusCode, 200)
217 | t.equal(response.headers['content-type'], 'application/json; charset=utf-8')
218 | t.same(response.json(), { hello: 'world' })
219 | })
220 | })
221 | ```
222 |
223 | ### 测试正在运行的服务器
224 | 你还可以在 fastify.listen() 启动服务器之后,或是 fastify.ready() 初始化路由与插件之后,进行 Fastify 的测试。
225 |
226 | #### 举例:
227 |
228 | 使用之前例子的 **app.js**。
229 |
230 | **test-listen.js** (用 [`Request`](https://www.npmjs.com/package/request) 测试)
231 | ```js
232 | const tap = require('tap')
233 | const request = require('request')
234 | const buildFastify = require('./app')
235 |
236 | tap.test('GET `/` route', t => {
237 | t.plan(5)
238 |
239 | const fastify = buildFastify()
240 |
241 | t.teardown(() => fastify.close())
242 |
243 | fastify.listen(0, (err) => {
244 | t.error(err)
245 |
246 | request({
247 | method: 'GET',
248 | url: 'http://localhost:' + fastify.server.address().port
249 | }, (err, response, body) => {
250 | t.error(err)
251 | t.equal(response.statusCode, 200)
252 | t.equal(response.headers['content-type'], 'application/json; charset=utf-8')
253 | t.same(JSON.parse(body), { hello: 'world' })
254 | })
255 | })
256 | })
257 | ```
258 |
259 | **test-ready.js** (用 [`SuperTest`](https://www.npmjs.com/package/supertest) 测试)
260 | ```js
261 | const tap = require('tap')
262 | const supertest = require('supertest')
263 | const buildFastify = require('./app')
264 |
265 | tap.test('GET `/` route', async (t) => {
266 | const fastify = buildFastify()
267 |
268 | t.teardown(() => fastify.close())
269 |
270 | await fastify.ready()
271 |
272 | const response = await supertest(fastify.server)
273 | .get('/')
274 | .expect(200)
275 | .expect('Content-Type', 'application/json; charset=utf-8')
276 | t.same(response.body, { hello: 'world' })
277 | })
278 | ```
279 |
280 | ### 如何检测 tap 的测试
281 | 1. 设置 `{only: true}` 选项,将需要检测的测试与其他测试分离
282 | ```javascript
283 | test('should ...', {only: true}, t => ...)
284 | ```
285 | 2. 通过 `npx` 运行 `tap`
286 | ```bash
287 | > npx tap -O -T --node-arg=--inspect-brk test/
288 | ```
289 | - `-O` 表示开启 `only` 选项,只运行设置了 `{only: true}` 的测试
290 | - `-T` 表示不设置超时
291 | - `--node-arg=--inspect-brk` 会启动 node 调试工具
292 | 3. 在 VS Code 中创建并运行一个 `Node.js: Attach` 调试配置,不需要额外修改。
293 |
294 | 现在你便可以在编辑器中检测你的测试文件 (以及 `Fastify` 的其他部分) 了。
--------------------------------------------------------------------------------
/docs/Validation-and-Serialization.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | ## 验证和序列化
4 | Fastify 使用基于 schema 的途径,从本质上将 schema 编译成了高性能的函数,来实现路由的验证与输出的序列化。我们推荐使用 [JSON Schema](https://json-schema.org/),虽然这并非必要。
5 |
6 | > ## ⚠ 安全须知
7 | > 应当将 schema 的定义写入代码。
8 | > 因为不管是验证还是序列化,都会使用 `new Function()` 来动态生成代码并执行。
9 | > 所以,用户提供的 schema 是不安全的。
10 | > 更多内容,请看 [Ajv](https://npm.im/ajv) 与 [fast-json-stringify](https://npm.im/fast-json-stringify)。
11 |
12 | ### 核心观念
13 | 验证与序列化的任务分别由两个可定制的工具完成:
14 | - [Ajv 6](https://www.npmjs.com/package/ajv/v/6.12.6) 用于验证请求。
15 | - [fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) 用于序列化响应的 body。
16 |
17 | 这些工具相互独立,但共享通过 `.addSchema(schema)` 方法添加到 Fastify 实例上的 JSON schema。
18 |
19 |
20 | #### 添加共用 schema (shared schema)
21 | 得益于 `addSchema` API,你能向 Fastify 实例添加多个 schema,并在程序的不同部分复用它们。
22 | 像往常一样,该 API 是封装好的。
23 |
24 | 共用 schema 可以通过 JSON Schema 的 [**`$ref`**](https://tools.ietf.org/html/draft-handrews-json-schema-01#section-8) 关键字复用。
25 | 以下是引用方法的 _总结_:
26 |
27 | + `myField: { $ref: '#foo'}` 将在当前 schema 内搜索 `$id: '#foo'` 字段。
28 | + `myField: { $ref: '#/definitions/foo'}` 将在当前 schema 内搜索 `definitions.foo` 字段。
29 | + `myField: { $ref: 'http://url.com/sh.json#'}` 会搜索含 `$id: 'http://url.com/sh.json'` 的共用 schema。
30 | + `myField: { $ref: 'http://url.com/sh.json#/definitions/foo'}` 会搜索含 `$id: 'http://url.com/sh.json'` 的共用 schema,并使用其 `definitions.foo` 字段。
31 | + `myField: { $ref: 'http://url.com/sh.json#foo'}` 会搜索含 `$id: 'http://url.com/sh.json'` 的共用 schema,并使用其内部带 `$id: '#foo'` 的对象。
32 |
33 |
34 | **简单用法:**
35 |
36 | ```js
37 | fastify.addSchema({
38 | $id: 'http://example.com/',
39 | type: 'object',
40 | properties: {
41 | hello: { type: 'string' }
42 | }
43 | })
44 |
45 | fastify.post('/', {
46 | handler () {},
47 | schema: {
48 | body: {
49 | type: 'array',
50 | items: { $ref: 'http://example.com#/properties/hello' }
51 | }
52 | }
53 | })
54 | ```
55 |
56 | **`$ref` 作为根引用 (root reference):**
57 |
58 | ```js
59 | fastify.addSchema({
60 | $id: 'commonSchema',
61 | type: 'object',
62 | properties: {
63 | hello: { type: 'string' }
64 | }
65 | })
66 |
67 | fastify.post('/', {
68 | handler () {},
69 | schema: {
70 | body: { $ref: 'commonSchema#' },
71 | headers: { $ref: 'commonSchema#' }
72 | }
73 | })
74 | ```
75 |
76 |
77 | #### 获取共用 schema
78 |
79 | 当自定义验证器或序列化器的时候,Fastify 不再能控制它们,此时 `.addSchema` 方法失去了作用。
80 | 要获取添加到 Fastify 实例上的 schema,你可以使用 `.getSchemas()`:
81 |
82 | ```js
83 | fastify.addSchema({
84 | $id: 'schemaId',
85 | type: 'object',
86 | properties: {
87 | hello: { type: 'string' }
88 | }
89 | })
90 |
91 | const mySchemas = fastify.getSchemas()
92 | const mySchema = fastify.getSchema('schemaId')
93 | ```
94 |
95 | `getSchemas` 方法也是封装好的,返回的是指定作用域中可用的共用 schema:
96 |
97 | ```js
98 | fastify.addSchema({ $id: 'one', my: 'hello' })
99 | // 只返回 schema `one`
100 | fastify.get('/', (request, reply) => { reply.send(fastify.getSchemas()) })
101 |
102 | fastify.register((instance, opts, done) => {
103 | instance.addSchema({ $id: 'two', my: 'ciao' })
104 | // 会返回 schema `one` 与 `two`
105 | instance.get('/sub', (request, reply) => { reply.send(instance.getSchemas()) })
106 |
107 | instance.register((subinstance, opts, done) => {
108 | subinstance.addSchema({ $id: 'three', my: 'hola' })
109 | // 会返回 schema `one`、`two` 和 `three`
110 | subinstance.get('/deep', (request, reply) => { reply.send(subinstance.getSchemas()) })
111 | done()
112 | })
113 | done()
114 | })
115 | ```
116 |
117 | ### 验证
118 | 路由的验证是依赖 [Ajv 6](https://www.npmjs.com/package/ajv/v/6.12.6) 实现的。这是一个高性能的 JSON schema 校验工具。验证输入十分简单,只需将字段加入路由的 schema 中即可!
119 |
120 | 支持的验证类型如下:
121 | - `body`:当请求方法为 POST、PUT 或 PATCH 时,验证 body。
122 | - `querystring` 或 `query`:验证 querystring。
123 | - `params`:验证路由参数。
124 | - `headers`:验证 header。
125 |
126 | 所有的验证都可以是一个完整的 JSON Schema 对象 (包括值为 `object` 的 `type` 属性以及包含参数的 `properties` 对象),也可以是一个没有 `type` 与 `properties`,而仅仅在顶层列明参数的简单变种 (见下文示例)。
127 |
128 | > ℹ 想要使用最新版 Ajv (Ajv 8) 的话,请查阅 [`schemaController`](Server.md#schema-controller) 一节,里边描述了比自定义校验器更简单的方法。
129 |
130 | 示例:
131 | ```js
132 | const bodyJsonSchema = {
133 | type: 'object',
134 | required: ['requiredKey'],
135 | properties: {
136 | someKey: { type: 'string' },
137 | someOtherKey: { type: 'number' },
138 | requiredKey: {
139 | type: 'array',
140 | maxItems: 3,
141 | items: { type: 'integer' }
142 | },
143 | nullableKey: { type: ['number', 'null'] }, // 或 { type: 'number', nullable: true }
144 | multipleTypesKey: { type: ['boolean', 'number'] },
145 | multipleRestrictedTypesKey: {
146 | oneOf: [
147 | { type: 'string', maxLength: 5 },
148 | { type: 'number', minimum: 10 }
149 | ]
150 | },
151 | enumKey: {
152 | type: 'string',
153 | enum: ['John', 'Foo']
154 | },
155 | notTypeKey: {
156 | not: { type: 'array' }
157 | }
158 | }
159 | }
160 |
161 | const queryStringJsonSchema = {
162 | type: 'object',
163 | properties: {
164 | name: { type: 'string' },
165 | excitement: { type: 'integer' }
166 | }
167 | }
168 |
169 | const paramsJsonSchema = {
170 | type: 'object',
171 | properties: {
172 | par1: { type: 'string' },
173 | par2: { type: 'number' }
174 | }
175 | }
176 |
177 | const headersJsonSchema = {
178 | type: 'object',
179 | properties: {
180 | 'x-foo': { type: 'string' }
181 | },
182 | required: ['x-foo']
183 | }
184 |
185 | const schema = {
186 | body: bodyJsonSchema,
187 | querystring: queryStringJsonSchema,
188 | params: paramsJsonSchema,
189 | headers: headersJsonSchema
190 | }
191 |
192 | fastify.post('/the/url', { schema }, handler)
193 | ```
194 |
195 | *请注意,为了通过校验,并在后续过程中使用正确类型的数据,Ajv 会尝试将数据[隐式转换](https://github.com/epoberezkin/ajv#coercing-data-types)为 schema 中 `type` 属性指明的类型。*
196 |
197 | Fastify 提供给 Ajv 的默认配置并不支持隐式转换 querystring 中的数组参数。但是,Fastify 允许你通过设置 Ajv 实例的 [`customOptions`](Server.md#ajv) 选项为 'array',来将参数转换为数组。举例如下:
198 |
199 | ```js
200 | const opts = {
201 | schema: {
202 | querystring: {
203 | type: 'object',
204 | properties: {
205 | ids: {
206 | type: 'array',
207 | default: []
208 | },
209 | },
210 | }
211 | }
212 | }
213 |
214 | fastify.get('/', opts, (request, reply) => {
215 | reply.send({ params: request.query })
216 | })
217 |
218 | fastify.listen(3000, (err) => {
219 | if (err) throw err
220 | })
221 | ```
222 |
223 | 默认情况下,该处的请求将返回 `400`:
224 |
225 | ```sh
226 | curl -X GET "http://localhost:3000/?ids=1
227 |
228 | {"statusCode":400,"error":"Bad Request","message":"querystring/hello should be array"}
229 | ```
230 |
231 | 设置 `coerceTypes` 的值为 'array' 将修复该问题:
232 |
233 | ```js
234 | const ajv = new Ajv({
235 | removeAdditional: true,
236 | useDefaults: true,
237 | coerceTypes: 'array', // 看这里
238 | allErrors: true
239 | })
240 |
241 | fastify.setValidatorCompiler(({ schema, method, url, httpPart }) => {
242 | return ajv.compile(schema)
243 | })
244 | ```
245 |
246 | ```sh
247 | curl -X GET "http://localhost:3000/?ids=1
248 |
249 | {"params":{"hello":["1"]}}
250 | ```
251 |
252 | 你还可以给每个参数类型 (body, query string, param, header) 都自定义 schema 校验器。
253 |
254 | 下面的例子改变了 ajv 的默认选项,禁用了 `body` 的强制类型转换。
255 |
256 | ```js
257 | const schemaCompilers = {
258 | body: new Ajv({
259 | removeAdditional: false,
260 | coerceTypes: false,
261 | allErrors: true
262 | }),
263 | params: new Ajv({
264 | removeAdditional: false,
265 | coerceTypes: true,
266 | allErrors: true
267 | }),
268 | querystring: new Ajv({
269 | removeAdditional: false,
270 | coerceTypes: true,
271 | allErrors: true
272 | }),
273 | headers: new Ajv({
274 | removeAdditional: false,
275 | coerceTypes: true,
276 | allErrors: true
277 | })
278 | }
279 |
280 | server.setValidatorCompiler(req => {
281 | if (!req.httpPart) {
282 | throw new Error('Missing httpPart')
283 | }
284 | const compiler = schemaCompilers[req.httpPart]
285 | if (!compiler) {
286 | throw new Error(`Missing compiler for ${req.httpPart}`)
287 | }
288 | return compiler.compile(req.schema)
289 | })
290 | ```
291 |
292 | 更多信息请看[这里](https://ajv.js.org/coercion.html)。
293 |
294 |
295 | #### Ajv 插件
296 |
297 | 你可以给默认的 `ajv` 实例提供一组插件。这些插件必须**兼容 Ajv 6**。
298 |
299 | > 插件格式参见 [`ajv 选项`](Server.md#ajv)
300 |
301 | ```js
302 | const fastify = require('fastify')({
303 | ajv: {
304 | plugins: [
305 | require('ajv-merge-patch')
306 | ]
307 | }
308 | })
309 |
310 | fastify.post('/', {
311 | handler (req, reply) { reply.send({ ok: 1 }) },
312 | schema: {
313 | body: {
314 | $patch: {
315 | source: {
316 | type: 'object',
317 | properties: {
318 | q: {
319 | type: 'string'
320 | }
321 | }
322 | },
323 | with: [
324 | {
325 | op: 'add',
326 | path: '/properties/q',
327 | value: { type: 'number' }
328 | }
329 | ]
330 | }
331 | }
332 | }
333 | })
334 |
335 | fastify.post('/foo', {
336 | handler (req, reply) { reply.send({ ok: 1 }) },
337 | schema: {
338 | body: {
339 | $merge: {
340 | source: {
341 | type: 'object',
342 | properties: {
343 | q: {
344 | type: 'string'
345 | }
346 | }
347 | },
348 | with: {
349 | required: ['q']
350 | }
351 | }
352 | }
353 | }
354 | })
355 | ```
356 |
357 |
358 | #### 验证生成器
359 |
360 | `validatorCompiler` 返回一个用于验证 body、URL、路由参数、header 以及 querystring 的函数。默认返回一个实现了 [ajv](https://ajv.js.org/) 验证接口的函数。Fastify 内在地使用该函数以加速验证。
361 |
362 | Fastify 使用的 [ajv 基本配置](https://github.com/epoberezkin/ajv#options-to-modify-validated-data)如下:
363 |
364 | ```js
365 | {
366 | removeAdditional: true, // 移除额外属性
367 | useDefaults: true, // 当属性或项目缺失时,使用 schema 中预先定义好的 default 的值代替
368 | coerceTypes: true, // 根据定义的 type 的值改变数据类型
369 | nullable: true // 支持 OpenAPI Specification 3.0 版本的 "nullable" 关键字
370 | }
371 | ```
372 |
373 | 上述配置可通过 [`ajv.customOptions`](Server.md#factory-ajv) 修改。
374 |
375 | 假如你想改变或增加额外的选项,你需要创建一个自定义的实例,并覆盖已存在的实例:
376 |
377 | ```js
378 | const fastify = require('fastify')()
379 | const Ajv = require('ajv')
380 | const ajv = new Ajv({
381 | // fastify 使用的默认参数(如果需要)
382 | removeAdditional: true,
383 | useDefaults: true,
384 | coerceTypes: true,
385 | nullable: true,
386 | // 任意其他参数
387 | // ...
388 | })
389 | fastify.setValidatorCompiler(({ schema, method, url, httpPart }) => {
390 | return ajv.compile(schema)
391 | })
392 | ```
393 |
394 | _**注意:** 如果你使用自定义校验工具的实例(即使是 Ajv),你应当向该实例而非 Fastify 添加 schema,因为在这种情况下,Fastify 默认的校验工具不再使用,而 `addSchema` 方法也不清楚你在使用什么工具进行校验。_
395 |
396 |
397 | ##### 使用其他验证工具
398 |
399 | 通过 `setValidatorCompiler` 函数,你可以轻松地将 `ajv` 替换为几乎任意的 Javascript 验证工具 (如 [joi](https://github.com/hapijs/joi/)、[yup](https://github.com/jquense/yup/) 等),或自定义它们。
400 |
401 | ```js
402 | const Joi = require('@hapi/joi')
403 |
404 | fastify.post('/the/url', {
405 | schema: {
406 | body: Joi.object().keys({
407 | hello: Joi.string().required()
408 | }).required()
409 | },
410 | validatorCompiler: ({ schema, method, url, httpPart }) => {
411 | return data => schema.validate(data)
412 | }
413 | }, handler)
414 | ```
415 |
416 | ```js
417 | const yup = require('yup')
418 | // 等同于前文 ajv 基本配置的 yup 的配置
419 | const yupOptions = {
420 | strict: false,
421 | abortEarly: false, // 返回所有错误(译注:为 true 时出现首个错误后即返回)
422 | stripUnknown: true, // 移除额外属性
423 | recursive: true
424 | }
425 | fastify.post('/the/url', {
426 | schema: {
427 | body: yup.object({
428 | age: yup.number().integer().required(),
429 | sub: yup.object().shape({
430 | name: yup.string().required()
431 | }).required()
432 | })
433 | },
434 | validatorCompiler: ({ schema, method, url, httpPart }) => {
435 | return function (data) {
436 | // 当设置 strict = false 时, yup 的 `validateSync` 函数在验证成功后会返回经过转换的值,而失败时则会抛错。
437 | try {
438 | const result = schema.validateSync(data, yupOptions)
439 | return { value: result }
440 | } catch (e) {
441 | return { error: e }
442 | }
443 | }
444 | }
445 | }, handler)
446 | ```
447 |
448 | ##### 其他验证工具的验证信息
449 |
450 | Fastify 的错误验证与其默认的验证引擎 `ajv` 紧密结合,错误最终会经由 `schemaErrorsText` 函数转化为便于阅读的信息。然而,也正是由于 `schemaErrorsText` 与 `ajv` 的强关联性,当你使用其他校验工具时,可能会出现奇怪或不完整的错误信息。
451 |
452 | 要规避以上问题,主要有两个途径:
453 |
454 | 1. 确保自定义的 `schemaCompiler` 返回的错误结构与 `ajv` 的一致 (当然,由于各引擎的差异,这是件困难的活儿)。
455 | 2. 使用自定义的 `errorHandler` 拦截并格式化验证错误。
456 |
457 | Fastify 给所有的验证错误添加了两个属性,来帮助你自定义 `errorHandler`:
458 |
459 | * validation:来自 `schemaCompiler` 函数的验证函数所返回的对象上的 `error` 属性的内容。
460 | * validationContext:验证错误的上下文 (body、params、query、headers)。
461 |
462 | 以下是一个自定义 `errorHandler` 来处理验证错误的例子:
463 |
464 | ```js
465 | const errorHandler = (error, request, reply) => {
466 | const statusCode = error.statusCode
467 | let response
468 |
469 | const { validation, validationContext } = error
470 |
471 | // 检验是否发生了验证错误
472 | if (validation) {
473 | response = {
474 | // validationContext 的值可能是 'body'、'params'、'headers' 或 'query'
475 | message: `A validation error occured when validating the ${validationContext}...`,
476 | // 验证工具返回的结果
477 | errors: validation
478 | }
479 | } else {
480 | response = {
481 | message: 'An error occurred...'
482 | }
483 | }
484 |
485 | // 其余代码。例如,记录错误日志。
486 | // ...
487 |
488 | reply.status(statusCode).send(response)
489 | }
490 | ```
491 |
492 |
493 | ### 序列化
494 | 通常,你会通过 JSON 格式将数据发送至客户端。鉴于此,Fastify 提供了一个强大的工具——[fast-json-stringify](https://www.npmjs.com/package/fast-json-stringify) 来帮助你。当你在路由选项中提供了输出的 schema 时,它能派上用场。
495 | 我们推荐你编写一个输出的 schema,因为这能让应用的吞吐量提升 100-400% (根据 payload 的不同而有所变化),也能防止敏感信息的意外泄露。
496 |
497 | 示例:
498 | ```js
499 | const schema = {
500 | response: {
501 | 200: {
502 | type: 'object',
503 | properties: {
504 | value: { type: 'string' },
505 | otherValue: { type: 'boolean' }
506 | }
507 | }
508 | }
509 | }
510 |
511 | fastify.post('/the/url', { schema }, handler)
512 | ```
513 |
514 | 如你所见,响应的 schema 是建立在状态码的基础之上的。当你想对多个状态码使用同一个 schema 时,你可以使用类似 `'2xx'` 的表达方法,例如:
515 | ```js
516 | const schema = {
517 | response: {
518 | '2xx': {
519 | type: 'object',
520 | properties: {
521 | value: { type: 'string' },
522 | otherValue: { type: 'boolean' }
523 | }
524 | },
525 | 201: {
526 | // 对比写法
527 | value: { type: 'string' }
528 | }
529 | }
530 | }
531 |
532 | fastify.post('/the/url', { schema }, handler)
533 | ```
534 |
535 |
536 | #### 序列化函数生成器
537 |
538 | `serializerCompiler` 返回一个根据输入参数返回字符串的函数。你应该提供一个函数,用于序列化所有定义了 `response` JSON Schema 的路由。
539 |
540 | ```js
541 | fastify.setSerializerCompiler(({ schema, method, url, httpStatus }) => {
542 | return data => JSON.stringify(data)
543 | })
544 |
545 | fastify.get('/user', {
546 | handler (req, reply) {
547 | reply.send({ id: 1, name: 'Foo', image: 'BIG IMAGE' })
548 | },
549 | schema: {
550 | response: {
551 | '2xx': {
552 | id: { type: 'number' },
553 | name: { type: 'string' }
554 | }
555 | }
556 | }
557 | })
558 | ```
559 |
560 | *假如你需要在特定位置使用自定义的序列化工具,你可以使用 [`reply.serializer(...)`](Reply.md#serializerfunc)。*
561 |
562 | ### 错误控制
563 | 当某个请求 schema 校验失败时,Fastify 会自动返回一个包含校验结果的 400 响应。举例来说,假如你的路由有一个如下的 schema:
564 | ```js
565 | const schema = {
566 | body: {
567 | type: 'object',
568 | properties: {
569 | name: { type: 'string' }
570 | },
571 | required: ['name']
572 | }
573 | }
574 | ```
575 | 当校验失败时,路由会立即返回一个包含以下内容的响应:
576 | ```js
577 | {
578 | "statusCode": 400,
579 | "error": "Bad Request",
580 | "message": "body should have required property 'name'"
581 | }
582 | ```
583 |
584 | 如果你想在路由内部控制错误,可以设置 `attachValidation` 选项。当出现 _验证错误_ 时,请求的 `validationError` 属性将会包含一个 `Error` 对象,在这对象内部有原始的验证结果 `validation`,如下所示:
585 | ```js
586 | const fastify = Fastify()
587 | fastify.post('/', { schema, attachValidation: true }, function (req, reply) {
588 | if (req.validationError) {
589 | // `req.validationError.validation` 包含了原始的验证错误信息
590 | reply.code(400).send(req.validationError)
591 | }
592 | })
593 | ```
594 |
595 | #### `schemaErrorFormatter`
596 |
597 | 如果你需要自定义错误的格式化,可以给 Fastify 实例化时的选项添加 `schemaErrorFormatter`,其值为返回一个错误的同步函数。函数的 this 指向 Fastify 服务器实例。
598 |
599 | `errors` 是 Fastify schema 错误 (`FastifySchemaValidationError`) 的一个数组。
600 | `dataVar` 是当前验证的 schema 片段 (params | body | querystring | headers)。
601 |
602 | ```js
603 | const fastify = Fastify({
604 | schemaErrorFormatter: (errors, dataVar) => {
605 | // ... 自定义的格式化逻辑
606 | return new Error(myErrorMessage)
607 | }
608 | })
609 |
610 | // 或
611 | fastify.setSchemaErrorFormatter(function (errors, dataVar) {
612 | this.log.error({ err: errors }, 'Validation failed')
613 | // ... 自定义的格式化逻辑
614 | return new Error(myErrorMessage)
615 | })
616 | ```
617 |
618 | 你还可以使用 [setErrorHandler](https://www.fastify.io/docs/latest/Server/#seterrorhandler) 方法来自定义一个校验错误响应,如下:
619 | ```js
620 | fastify.setErrorHandler(function (error, request, reply) {
621 | if (error.validation) {
622 | // error.validationContext 是 [body, params, querystring, headers] 之中的值
623 | reply.status(422).send(new Error(`validation failed of the ${error.validationContext}`))
624 | }
625 | })
626 | ```
627 |
628 | 假如你想轻松愉快地自定义错误响应,请查看 [`ajv-errors`](https://github.com/epoberezkin/ajv-errors)。具体的例子可以移步[这里](https://github.com/fastify/example/blob/HEAD/validation-messages/custom-errors-messages.js)。
629 |
630 |
631 | 下面的例子展示了如何通过自定义 AJV,为 schema 的**每个属性添加自定义错误信息**。
632 | 其中的注释描述了在不同场景下设置不同信息的方法。
633 |
634 | ```js
635 | const fastify = Fastify({
636 | ajv: {
637 | customOptions: { jsonPointers: true },
638 | plugins: [
639 | require('ajv-errors')
640 | ]
641 | }
642 | })
643 |
644 | const schema = {
645 | body: {
646 | type: 'object',
647 | properties: {
648 | name: {
649 | type: 'string',
650 | errorMessage: {
651 | type: 'Bad name'
652 | }
653 | },
654 | age: {
655 | type: 'number',
656 | errorMessage: {
657 | type: 'Bad age', // 为除了必填外的所有限制
658 | min: 'Too young' // 自定义错误信息
659 | }
660 | }
661 | },
662 | required: ['name', 'age'],
663 | errorMessage: {
664 | required: {
665 | name: 'Why no name!', // 为必填设置
666 | age: 'Why no age!' // 错误信息
667 | }
668 | }
669 | }
670 | }
671 |
672 | fastify.post('/', { schema, }, (request, reply) => {
673 | reply.send({
674 | hello: 'world'
675 | })
676 | })
677 | ```
678 |
679 | 想要本地化错误信息,请看 [ajv-i18n](https://github.com/epoberezkin/ajv-i18n)
680 |
681 | ```js
682 | const localize = require('ajv-i18n')
683 |
684 | const fastify = Fastify()
685 |
686 | const schema = {
687 | body: {
688 | type: 'object',
689 | properties: {
690 | name: {
691 | type: 'string',
692 | },
693 | age: {
694 | type: 'number',
695 | }
696 | },
697 | required: ['name', 'age'],
698 | }
699 | }
700 |
701 | fastify.setErrorHandler(function (error, request, reply) {
702 | if (error.validation) {
703 | localize.ru(error.validation)
704 | reply.status(400).send(error.validation)
705 | return
706 | }
707 | reply.send(error)
708 | })
709 | ```
710 |
711 | ### JSON Schema 支持
712 |
713 | 为了能更简单地重用 schema,JSON Schema 提供了一些功能,来结合 Fastify 的共用 schema。
714 |
715 | | 用例 | 验证器 | 序列化器 |
716 | |-----------------------------------|-----------|------------|
717 | | 引用 (`$ref`) `$id` | ✔ | ✔️ |
718 | | 引用 (`$ref`) `/definitions` | ✔️ | ✔️ |
719 | | 引用 (`$ref`) 共用 schema `$id` | ✔ | ✔️ |
720 | | 引用 (`$ref`) 共用 schema `/definitions` | ✔ | ✔️ |
721 |
722 | #### 示例
723 |
724 | ##### 同一个 JSON Schema 中对 `$id` 的引用 ($ref)
725 |
726 | ```js
727 | const refToId = {
728 | type: 'object',
729 | definitions: {
730 | foo: {
731 | $id: '#address',
732 | type: 'object',
733 | properties: {
734 | city: { type: 'string' }
735 | }
736 | }
737 | },
738 | properties: {
739 | home: { $ref: '#address' },
740 | work: { $ref: '#address' }
741 | }
742 | }
743 | ```
744 |
745 | ##### 同一个 JSON Schema 中对 `/definitions` 的引用 ($ref)
746 | ```js
747 | const refToDefinitions = {
748 | type: 'object',
749 | definitions: {
750 | foo: {
751 | $id: '#address',
752 | type: 'object',
753 | properties: {
754 | city: { type: 'string' }
755 | }
756 | }
757 | },
758 | properties: {
759 | home: { $ref: '#/definitions/foo' },
760 | work: { $ref: '#/definitions/foo' }
761 | }
762 | }
763 | ```
764 |
765 | ##### 对外部共用 schema 的 `$id` 的引用 ($ref)
766 | ```js
767 | fastify.addSchema({
768 | $id: 'http://foo/common.json',
769 | type: 'object',
770 | definitions: {
771 | foo: {
772 | $id: '#address',
773 | type: 'object',
774 | properties: {
775 | city: { type: 'string' }
776 | }
777 | }
778 | }
779 | })
780 |
781 | const refToSharedSchemaId = {
782 | type: 'object',
783 | properties: {
784 | home: { $ref: 'http://foo/common.json#address' },
785 | work: { $ref: 'http://foo/common.json#address' }
786 | }
787 | }
788 | ```
789 |
790 | ##### 对外部共用 schema 的 `/definitions` 的引用 ($ref)
791 | ```js
792 | fastify.addSchema({
793 | $id: 'http://foo/shared.json',
794 | type: 'object',
795 | definitions: {
796 | foo: {
797 | type: 'object',
798 | properties: {
799 | city: { type: 'string' }
800 | }
801 | }
802 | }
803 | })
804 |
805 | const refToSharedSchemaDefinitions = {
806 | type: 'object',
807 | properties: {
808 | home: { $ref: 'http://foo/shared.json#/definitions/foo' },
809 | work: { $ref: 'http://foo/shared.json#/definitions/foo' }
810 | }
811 | }
812 | ```
813 |
814 |
815 | ### 资源
816 | - [JSON Schema](https://json-schema.org/)
817 | - [理解 JSON Schema](https://spacetelescope.github.io/understanding-json-schema/)
818 | - [fast-json-stringify 文档](https://github.com/fastify/fast-json-stringify)
819 | - [Ajv 文档](https://github.com/epoberezkin/ajv/blob/master/README.md)
820 | - [Ajv i18n](https://github.com/epoberezkin/ajv-i18n)
821 | - [Ajv 自定义错误](https://github.com/epoberezkin/ajv-errors)
822 | - 使用核心方法自定义错误处理,并实现错误文件转储的[例子](https://github.com/fastify/example/tree/main/validation-messages)
--------------------------------------------------------------------------------
/docs/Write-Plugin.md:
--------------------------------------------------------------------------------
1 | Fastify
2 |
3 | # 如何写一个好的插件
4 | 首先,要感谢你决定为 Fastify 编写插件。Fastify 本身是一个极简的框架,插件才是它强大功能的来源,所以,谢谢你。
5 | Fastify 的核心原则是高性能、低成本、提供优秀的用户体验。当编写插件时,这些原则应当被遵循。因此,本文我们将会分析一个优质的插件所具有的特征。
6 |
7 | *需要一些灵感?你可以在 issue 中使用 ["plugin suggestion"](https://github.com/fastify/fastify/issues?q=is%3Aissue+is%3Aopen+label%3A%22plugin+suggestion%22) 标签!*
8 |
9 | ## 代码
10 | Fastify 运用了不同的技术来优化代码,其大部分都被写入了文档。我们强烈建议你阅读 [插件指南](Plugins-Guide.md) 一文,以了解所有可用于构建插件的 API 及其用法。
11 |
12 | 存有疑虑或寻求建议?我们非常高兴能帮助你!只需在我们的 [求助仓库](https://github.com/fastify/help) 提一个 issue 即可!
13 |
14 | 一旦你向我们的 [生态列表](https://github.com/fastify/fastify/blob/main/docs/Ecosystem.md) 提交了一个插件,我们将会检查你的代码,需要时也会帮忙改进它。
15 |
16 | ## 文档
17 | 文档相当重要。假如你的插件没有好的文档,我们将拒绝将其加入生态列表。缺乏良好的文档会提升用户使用插件的难度,并有可能导致弃用。
18 | 以下列出了一些优秀插件文档的示例:
19 | - [`fastify-caching`](https://github.com/fastify/fastify-caching)
20 | - [`fastify-compress`](https://github.com/fastify/fastify-compress)
21 | - [`fastify-cookie`](https://github.com/fastify/fastify-cookie)
22 | - [`point-of-view`](https://github.com/fastify/point-of-view)
23 | - [`under-pressure`](https://github.com/fastify/under-pressure)
24 |
25 | ## 许可证
26 | 你可以为你的插件使用自己偏好的许可,我们不会强求。
27 | 我们推荐 [MIT 许可证](https://choosealicense.com/licenses/mit/),因为我们认为它允许更多人自由地使用代码。其他可替代的许可证参见 [OSI list](https://opensource.org/licenses) 或 GitHub 的 [choosealicense.com](https://choosealicense.com/)。
28 |
29 | ## 示例
30 | 总在你的仓库里添加一个示例文件。这对于用户是相当有帮助的,也提供了一个快速的手段来测试你的插件。使用者们会为此感激的。
31 |
32 | ## 测试
33 | 彻底地测试一个插件,来验证其是否正常执行,是极为重要的。
34 | 缺乏测试会影响用户的信任感,也无法保证代码在不同版本的依赖下还能正常工作。
35 |
36 | 我们不强求使用某一测试工具。我们使用的是 [`tap`](https://www.node-tap.org/),因为它提供了开箱即用的并行测试以及代码覆盖率检测。
37 |
38 | ## 代码检查
39 | 这一项不是强制的,但我们强烈推荐你在插件中使用一个代码检查工具。这可以帮助你保持统一的代码风格,同时避免许多错误。
40 |
41 | 我们使用 [`standard`](https://standardjs.com/),因为它不需任何配置,并且容易与测试集成。
42 |
43 | ## 持续集成
44 | 这一项也不是强制的,但假如你开源发布你的代码,持续集成能保证其他人的参与不会破坏你的插件,并检查插件是否如预期般工作。[CircleCI](https://circleci.com/) 和 [GitHub Actions](https://github.com/features/actions) 都是对开源项目免费的持续集成系统,且易于安装配置。
45 | 此外,你还可以启用 [Dependabot](https://dependabot.com/) 或 [Snyk](https://snyk.io/) 等服务,它可以帮你将依赖保持在最新版本,并检查在 Fastify 的新版本上你的插件是否存在问题。
46 |
47 | ## 让我们开始吧!
48 | 棒极了,现在你已经了解了如何为 Fastify 写一个好插件!
49 | 当你完成了一个插件(或更多)之后,请让我们知道!我们会将其添加到 [生态](https://github.com/fastify/fastify#ecosystem) 一节中!
50 |
51 | 想看更多真实的例子?请参阅:
52 | - [`point-of-view`](https://github.com/fastify/point-of-view)
53 | Fastify 的模板渲染 (*ejs, pug, handlebars, marko*) 插件。
54 | - [`fastify-mongodb`](https://github.com/fastify/fastify-mongodb)
55 | Fastify 的 MongoDB 连接插件,通过它你可以在你服务器的每个部分共享同一个 MongoDB 连接池。
56 | - [`fastify-multipart`](https://github.com/fastify/fastify-multipart)
57 | 为 Fastify 提供 mltipart 支持。
58 | - [`fastify-helmet`](https://github.com/fastify/fastify-helmet)
59 | 重要的请求头安全插件。
--------------------------------------------------------------------------------
/docs/resources/encapsulation_context.drawio:
--------------------------------------------------------------------------------
1 | 7ZpPk5owGMY/jcd2SCKIx0q3todOO+thjzsRAmQ2Eopx1f30DRKUNLCrncXN6uKMA0/+EN5feJNndICCxWZa4Dz9ySPCBtCJNgP0dQDhaDiS36WwrQQfOJWQFDSqJHAQZvSJKLGutqIRWWoVBedM0FwXQ55lJBSahouCr/VqMWf6XXOcEEOYhZiZ6h2NRKqewnUO+ndCk7S+M3BUyQLXlZWwTHHE1w0J3QxQUHAuqrPFJiCsjF0dl6rdt47S/cAKkoljGjyhO8+Z3U9YQP3bP1PHvc9+fFK9PGK2Ug98Ww4IOgHPBNkINXSxreOxTqkgsxyH5fVaIh+gSSoWTF4BeYqXeUUhphsibzyJKWMBZ7zYNUexW36k/kgKQWWYvzCaZLJM8LKngq+yqGy362wpCv5AGq293VH2KkfX0KtD6mZM6geUtyObhqRiNCV8QUSxlVVU6VDh2uqX6wN8d6y0tAF+L2I14ZJ9zwcm8kRhOQER6kL0m60SmhmE5DzLy9O84CFZytFMXmA2x+FDsov8r5VgNCNK12H8CzKOYRi2QYq8ued6rwMDOq5Gwzdp+C0wUF8shtfMYmwXC/eKWSDfLhbATFJG/MtQ5sc/+35Jx/O6B+fZmABPz9wAmUFBXktU+guLZ0QlSKncgHQvr/rcemGCdk299rX1lAn5POSXp+nbhXzUGfI3TQsRJn7cmha80CfzuBcKdan+XrS8FmfNFf4HIZOQXYjGBiJp7rIo7DF57cN/ZPLqHwrUmdQrbjO1wRYoALp9LbKOnW8OAZFLRm2Qxt4I4X5WmNqtjT7rOyEA3norZFrqq6cEkH2Y4AcmI+MhaB0m03EbYM5tLFCL2zrzLheY5vddO4thByubnAXodnOXsnE9HoOd1gJcvvv7D0SWMTL93/s3FydTsc9cmJ7PilfnFfdDJ0Oyz1zAy7eApyc4+8wFvHwPeHrGO6e5kJeHH9Z3ZY1/J6Cbvw==
--------------------------------------------------------------------------------
/docs/resources/encapsulation_context.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------