TypeScript
TypeScript
Fastify 框架是用普通 JavaScript 编写的,因此类型定义不太容易维护;然而,自版本 2 及更高版本以来,维护者和贡献者付出了巨大的努力来改进类型。
¥The Fastify framework is written in vanilla JavaScript, and as such type definitions are not as easy to maintain; however, since version 2 and beyond, maintainers and contributors have put in a great effort to improve the types.
Fastify 版本 3 中更改了类型系统。新的类型系统引入了通用约束和默认,以及定义模式类型(例如请求正文、查询字符串等)的新方法!由于团队致力于改进框架和类型定义协同作用,有时 API 的某些部分不会被键入或可能键入不正确。我们鼓励你做出贡献,帮助我们填补空白。在开始之前,请务必阅读我们的 CONTRIBUTING.md
文件,以确保一切顺利!
¥The type system was changed in Fastify version 3. The new type system introduces
generic constraining and defaulting, plus a new way to define schema types such
as a request body, querystring, and more! As the team works on improving
framework and type definition synergy, sometimes parts of the API will not be
typed or may be typed incorrectly. We encourage you to contribute to help us
fill in the gaps. Just make sure to read our
CONTRIBUTING.md
file before getting started to make sure things go smoothly!
本节中的文档涵盖 Fastify 版本 3.x 类型
¥The documentation in this section covers Fastify version 3.x typings
插件可能包含也可能不包含类型。有关更多信息,请参阅 插件。我们鼓励用户发送拉取请求以改善打字支持。
¥Plugins may or may not include typings. See Plugins for more information. We encourage users to send pull requests to improve typings support.
🚨 不要忘记安装 @types/node
¥🚨 Don't forget to install @types/node
通过实例学习
¥Learn By Example
学习 Fastify 类型系统的最佳方法是通过示例!以下四个示例应涵盖最常见的 Fastify 开发案例。示例之后还有关于类型系统的进一步、更详细的文档。
¥The best way to learn the Fastify type system is by example! The following four examples should cover the most common Fastify development cases. After the examples there is further, more detailed documentation for the type system.
入门
¥Getting Started
此示例将帮助你启动并运行 Fastify 和 TypeScript。它会导致一个空白的 http Fastify 服务器。
¥This example will get you up and running with Fastify and TypeScript. It results in a blank http Fastify server.
创建一个新的 npm 项目,安装 Fastify,并安装 typescript 和 Node.js 类型作为对等依赖:
¥Create a new npm project, install Fastify, and install typescript & Node.js types as peer dependencies:
npm init -y
npm i fastify
npm i -D typescript @types/node
将以下行添加到
package.json
的"scripts"
部分:¥Add the following lines to the
"scripts"
section of thepackage.json
:
{
"scripts": {
"build": "tsc -p tsconfig.json",
"start": "node index.js"
}
}
初始化 TypeScript 配置文件:
¥Initialize a TypeScript configuration file:
npx tsc --init
或者使用 推荐的 之一。
¥or use one of the recommended ones.
注意:将 tsconfig.json
中的 target
属性设置为 es2017
或更高以避免 FastifyDeprecation 警告。
¥Note: Set target
property in tsconfig.json
to es2017
or greater to avoid
FastifyDeprecation warning.
创建
index.ts
文件 - 这将包含服务器代码¥Create an
index.ts
file - this will contain the server code将以下代码块添加到你的文件中:
¥Add the following code block to your file:
import fastify from 'fastify'
const server = fastify()
server.get('/ping', async (request, reply) => {
return 'pong\n'
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})运行
npm run build
- 这会将index.ts
编译为index.js
,可以使用 Node.js 执行。如果你遇到任何错误,请在 fastify/help 中打开一个问题¥Run
npm run build
- this will compileindex.ts
intoindex.js
which can be executed using Node.js. If you run into any errors please open an issue in fastify/help运行
npm run start
以运行 Fastify 服务器¥Run
npm run start
to run the Fastify server你应该在控制台中看到
Server listening at http://127.0.0.1:8080
¥You should see
Server listening at http://127.0.0.1:8080
in your console使用
curl localhost:8080/ping
试用你的服务器,它应该返回pong
🏓¥Try out your server using
curl localhost:8080/ping
, it should returnpong
🏓
🎉 你现在已经有了一个可以运行的 Typescript Fastify 服务器!此示例演示了 3.x 版本类型系统的简单性。默认情况下,类型系统假定你正在使用 http
服务器。后面的示例将演示如何创建更复杂的服务器,例如 https
和 http2
、如何指定路由模式等等!
¥🎉 You now have a working Typescript Fastify server! This example demonstrates
the simplicity of the version 3.x type system. By default, the type system
assumes you are using an http
server. The later examples will demonstrate how
to create more complex servers such as https
and http2
, how to specify route
schemas, and more!
有关使用 TypeScript 初始化 Fastify 的更多示例(例如启用 HTTP2),请查看详细的 API 部分 此处
¥For more examples on initializing Fastify with TypeScript (such as enabling HTTP2) check out the detailed API section here
使用泛型
¥Using Generics
类型系统严重依赖泛型属性来提供最准确的开发体验。虽然有些人可能会觉得开销有点麻烦,但这种权衡是值得的!本示例将深入研究如何实现路由架构的泛型类型以及位于路由级 request
对象上的动态属性。
¥The type system heavily relies on generic properties to provide the most
accurate development experience. While some may find the overhead a bit
cumbersome, the tradeoff is worth it! This example will dive into implementing
generic types for route schemas and the dynamic properties located on the
route-level request
object.
如果你未完成前面的示例,请按照步骤 1-4 进行设置。
¥If you did not complete the previous example, follow steps 1-4 to get set up.
在
index.ts
内部,定义三个接口IQuerystring
、IHeaders
和IReply
:¥Inside
index.ts
, define three interfacesIQuerystring
,IHeaders
andIReply
:interface IQuerystring {
username: string;
password: string;
}
interface IHeaders {
'h-Custom': string;
}
interface IReply {
200: { success: boolean };
302: { url: string };
'4xx': { error: string };
}使用这三个接口,定义一个新的 API 路由并将它们作为泛型传递。简写路由方法(即
.get
)接受包含五个命名属性的通用对象RouteGenericInterface
:Body
、Querystring
、Params
、Headers
和Reply
。接口Body
、Querystring
、Params
和Headers
将通过路由方法传递到路由方法处理程序request
实例和Reply
接口到reply
实例。¥Using the three interfaces, define a new API route and pass them as generics. The shorthand route methods (i.e.
.get
) accept a generic objectRouteGenericInterface
containing five named properties:Body
,Querystring
,Params
,Headers
andReply
. The interfacesBody
,Querystring
,Params
andHeaders
will be passed down through the route method into the route method handlerrequest
instance and theReply
interface to thereply
instance.server.get<{
Querystring: IQuerystring,
Headers: IHeaders,
Reply: IReply
}>('/auth', async (request, reply) => {
const { username, password } = request.query
const customerHeader = request.headers['h-Custom']
// do something with request data
// chaining .statusCode/.code calls with .send allows type narrowing. For example:
// this works
reply.code(200).send({ success: true });
// but this gives a type error
reply.code(200).send('uh-oh');
// it even works for wildcards
reply.code(404).send({ error: 'Not found' });
return `logged in!`
})使用
npm run build
和npm run start
构建并运行服务器代码¥Build and run the server code with
npm run build
andnpm run start
查询 API
¥Query the API
curl localhost:8080/auth?username=admin&password=Password123!
它应该返回
logged in!
¥And it should return back
logged in!
但等等还有更多!通用接口也可在路由级别钩子方法内使用。通过添加
preValidation
钩子修改上一个路由:¥But wait there's more! The generic interfaces are also available inside route level hook methods. Modify the previous route by adding a
preValidation
hook:server.get<{
Querystring: IQuerystring,
Headers: IHeaders,
Reply: IReply
}>('/auth', {
preValidation: (request, reply, done) => {
const { username, password } = request.query
done(username !== 'admin' ? new Error('Must be admin') : undefined) // only validate `admin` account
}
}, async (request, reply) => {
const customerHeader = request.headers['h-Custom']
// do something with request data
return `logged in!`
})构建并运行查询,将
username
查询字符串选项设置为除admin
以外的任何值。API 现在应该返回 HTTP 500 错误{"statusCode":500,"error":"Internal Server Error","message":"Must be admin"}
¥Build and run and query with the
username
query string option set to anything other thanadmin
. The API should now return a HTTP 500 error{"statusCode":500,"error":"Internal Server Error","message":"Must be admin"}
🎉 干得好,现在你可以为每个路由定义接口,并具有严格类型化的请求和响应实例。Fastify 类型系统的其他部分依赖于通用属性。请务必参考下面的详细类型系统文档,以了解有关可用内容的更多信息。
¥🎉 Good work, now you can define interfaces for each route and have strictly typed request and reply instances. Other parts of the Fastify type system rely on generic properties. Make sure to reference the detailed type system documentation below to learn more about what is available.
JSON 结构
¥JSON Schema
要验证你的请求和响应,你可以使用 JSON 架构文件。如果你还不知道,为 Fastify 路由定义模式可以提高其吞吐量!查看 验证和序列化 文档以获取更多信息。
¥To validate your requests and responses you can use JSON Schema files. If you didn't know already, defining schemas for your Fastify routes can increase their throughput! Check out the Validation and Serialization documentation for more info.
它还具有在处理程序中使用定义的类型(包括预验证等)的优点。
¥Also it has the advantage to use the defined type within your handlers (including pre-validation, etc.).
以下是有关如何实现此目标的一些选项。
¥Here are some options on how to achieve this.
Fastify 类型提供商
¥Fastify Type Providers
Fastify 提供两个封装 json-schema-to-ts
和 typebox
的包:
¥Fastify offers two packages wrapping json-schema-to-ts
and typebox
:
以及第三方的 zod
封装器,名为 fastify-type-provider-zod
¥And a zod
wrapper by a third party called fastify-type-provider-zod
它们简化了模式验证设置,你可以在 类型提供者 页面中阅读有关它们的更多信息。
¥They simplify schema validation setup and you can read more about them in Type Providers page.
以下是如何使用没有类型提供程序的 typebox
、json-schema-to-typescript
和 json-schema-to-ts
包设置模式验证。
¥Below is how to setup schema validation using the typebox
,
json-schema-to-typescript
, and json-schema-to-ts
packages without type
providers.
TypeBox
用于同时构建类型和模式的有用库是 TypeBox。使用 TypeBox,你可以在代码中定义模式,并根据需要直接将它们用作类型或模式。
¥A useful library for building types and a schema at once is TypeBox. With TypeBox you define your schema within your code and use them directly as types or schemas as you need them.
当你想使用它来验证 fastify 路由中的某些有效负载时,你可以按如下方式操作:
¥When you want to use it for validation of some payload in a fastify route you can do it as follows:
在你的项目中安装
typebox
。¥Install
typebox
in your project.npm i @sinclair/typebox
使用
Type
定义所需的模式,并使用Static
创建相应的类型。¥Define the schema you need with
Type
and create the respective type withStatic
.import { Static, Type } from '@sinclair/typebox'
export const User = Type.Object({
name: Type.String(),
mail: Type.Optional(Type.String({ format: 'email' })),
})
export type UserType = Static<typeof User>在定义路由期间使用定义的类型和架构
¥Use the defined type and schema during the definition of your route
import Fastify from 'fastify'
// ...
const fastify = Fastify()
fastify.post<{ Body: UserType, Reply: UserType }>(
'/',
{
schema: {
body: User,
response: {
200: User
},
},
},
(request, reply) => {
// The `name` and `mail` types are automatically inferred
const { name, mail } = request.body;
reply.status(200).send({ name, mail });
}
)
json-schema-to-typescript
在最后一个示例中,我们使用 Typebox 来定义路由的类型和模式。许多用户已经在使用 JSON 模式来定义这些属性,幸运的是,有一种方法可以将现有的 JSON 模式转换为 TypeScript 接口!
¥In the last example we used Typebox to define the types and schemas for our route. Many users will already be using JSON Schemas to define these properties, and luckily there is a way to transform existing JSON Schemas into TypeScript interfaces!
如果你没有完成 '入门' 示例,请返回并首先按照步骤 1-4 进行操作。
¥If you did not complete the 'Getting Started' example, go back and follow steps 1-4 first.
安装
json-schema-to-typescript
模块:¥Install the
json-schema-to-typescript
module:npm i -D json-schema-to-typescript
创建一个名为
schemas
的新文件夹并添加两个文件headers.json
和querystring.json
。将以下架构定义复制并粘贴到相应的文件中:¥Create a new folder called
schemas
and add two filesheaders.json
andquerystring.json
. Copy and paste the following schema definitions into the respective files:{
"title": "Headers Schema",
"type": "object",
"properties": {
"h-Custom": { "type": "string" }
},
"additionalProperties": false,
"required": ["h-Custom"]
}{
"title": "Querystring Schema",
"type": "object",
"properties": {
"username": { "type": "string" },
"password": { "type": "string" }
},
"additionalProperties": false,
"required": ["username", "password"]
}将
compile-schemas
脚本添加到 package.json:¥Add a
compile-schemas
script to the package.json:
{
"scripts": {
"compile-schemas": "json2ts -i schemas -o types"
}
}
json2ts
是 json-schema-to-typescript
中包含的 CLI 实用程序。schemas
是输入路径,types
是输出路径。5.应该已经在 types
目录中创建了两个新文件。6.
¥json2ts
is a CLI utility included in json-schema-to-typescript
. schemas
is the input path, and types
is the output path.
5. Run npm run compile-schemas
. Two new files should have been created in the
types
directory.
6. Update index.ts
to have the following code:
import fastify from 'fastify'
// import json schemas as normal
import QuerystringSchema from './schemas/querystring.json'
import HeadersSchema from './schemas/headers.json'
// import the generated interfaces
import { QuerystringSchema as QuerystringSchemaInterface } from './types/querystring'
import { HeadersSchema as HeadersSchemaInterface } from './types/headers'
const server = fastify()
server.get<{
Querystring: QuerystringSchemaInterface,
Headers: HeadersSchemaInterface
}>('/auth', {
schema: {
querystring: QuerystringSchema,
headers: HeadersSchema
},
preValidation: (request, reply, done) => {
const { username, password } = request.query
done(username !== 'admin' ? new Error('Must be admin') : undefined)
}
// or if using async
// preValidation: async (request, reply) => {
// const { username, password } = request.query
// if (username !== "admin") throw new Error("Must be admin");
// }
}, async (request, reply) => {
const customerHeader = request.headers['h-Custom']
// do something with request data
return `logged in!`
})
server.route<{
Querystring: QuerystringSchemaInterface,
Headers: HeadersSchemaInterface
}>({
method: 'GET',
url: '/auth2',
schema: {
querystring: QuerystringSchema,
headers: HeadersSchema
},
preHandler: (request, reply, done) => {
const { username, password } = request.query
const customerHeader = request.headers['h-Custom']
done()
},
handler: (request, reply) => {
const { username, password } = request.query
const customerHeader = request.headers['h-Custom']
reply.status(200).send({username});
}
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(0)
}
console.log(`Server listening at ${address}`)
})
请特别注意此文件顶部的导入。这可能看起来多余,但你需要导入架构文件和生成的接口。
¥Pay special attention to the imports at the top of this file. It might seem redundant, but you need to import both the schema files and the generated interfaces.
做得好!现在你可以使用 JSON 模式和 TypeScript 定义。
¥Great work! Now you can make use of both JSON Schemas and TypeScript definitions.
json-schema-to-ts
如果你不想从架构中生成类型,而是想直接从代码中使用它们,则可以使用 json-schema-to-ts 包。
¥If you do not want to generate types from your schemas, but want to use them directly from your code, you can use the package json-schema-to-ts.
你可以将其安装为开发依赖。
¥You can install it as dev-dependency.
npm i -D json-schema-to-ts
在代码中,你可以像普通对象一样定义模式。但请注意将其设置为 const,如模块文档中所解释的那样。
¥In your code you can define your schema like a normal object. But be aware of making it const like explained in the docs of the module.
const todo = {
type: 'object',
properties: {
name: { type: 'string' },
description: { type: 'string' },
done: { type: 'boolean' },
},
required: ['name'],
} as const; // don't forget to use const !
使用提供的类型 FromSchema
,你可以从模式构建类型并在处理程序中使用它。
¥With the provided type FromSchema
you can build a type from your schema and
use it in your handler.
import { FromSchema } from "json-schema-to-ts";
fastify.post<{ Body: FromSchema<typeof todo> }>(
'/todo',
{
schema: {
body: todo,
response: {
201: {
type: 'string',
},
},
}
},
async (request, reply): Promise<void> => {
/*
request.body has type
{
[x: string]: unknown;
description?: string;
done?: boolean;
name: string;
}
*/
request.body.name // will not throw type error
request.body.notthere // will throw type error
reply.status(201).send();
},
);
插件
¥Plugins
Fastify 最显着的功能之一是其广泛的插件生态系统。插件类型完全受支持,并利用 声明合并 模式。该示例分为三个部分:创建 TypeScript Fastify 插件、为 Fastify 插件创建类型定义以及在 TypeScript 项目中使用 Fastify 插件。
¥One of Fastify's most distinguishable features is its extensive plugin ecosystem. Plugin types are fully supported, and take advantage of the declaration merging pattern. This example is broken up into three parts: Creating a TypeScript Fastify Plugin, Creating Type Definitions for a Fastify Plugin, and Using a Fastify Plugin in a TypeScript Project.
创建 TypeScript Fastify 插件
¥Creating a TypeScript Fastify Plugin
初始化一个新的 npm 项目并安装所需的依赖
¥Initialize a new npm project and install required dependencies
npm init -y
npm i fastify fastify-plugin
npm i -D typescript @types/node将
build
脚本添加到package.json
文件的"scripts"
部分,将'index.d.ts'
添加到"types"
部分:¥Add a
build
script to the"scripts"
section and'index.d.ts'
to the"types"
section of thepackage.json
file:{
"types": "index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.json"
}
}初始化 TypeScript 配置文件:
¥Initialize a TypeScript configuration file:
npx typescript --init
生成文件后,在
"compilerOptions"
对象中启用"declaration"
选项。¥Once the file is generated, enable the
"declaration"
option in the"compilerOptions"
object.{
"compilerOptions": {
"declaration": true
}
}创建
index.ts
文件 - 这将包含插件代码¥Create an
index.ts
file - this will contain the plugin code将以下代码添加到
index.ts
¥Add the following code to
index.ts
import { FastifyPluginCallback, FastifyPluginAsync } from 'fastify'
import fp from 'fastify-plugin'
// using declaration merging, add your plugin props to the appropriate fastify interfaces
// if prop type is defined here, the value will be typechecked when you call decorate{,Request,Reply}
declare module 'fastify' {
interface FastifyRequest {
myPluginProp: string
}
interface FastifyReply {
myPluginProp: number
}
}
// define options
export interface MyPluginOptions {
myPluginOption: string
}
// define plugin using callbacks
const myPluginCallback: FastifyPluginCallback<MyPluginOptions> = (fastify, options, done) => {
fastify.decorateRequest('myPluginProp', 'super_secret_value')
fastify.decorateReply('myPluginProp', options.myPluginOption)
done()
}
// define plugin using promises
const myPluginAsync: FastifyPluginAsync<MyPluginOptions> = async (fastify, options) => {
fastify.decorateRequest('myPluginProp', 'super_secret_value')
fastify.decorateReply('myPluginProp', options.myPluginOption)
}
// export plugin using fastify-plugin
export default fp(myPluginCallback, '3.x')
// or
// export default fp(myPluginAsync, '3.x')运行
npm run build
以编译插件代码并生成 JavaScript 源文件和类型定义文件。¥Run
npm run build
to compile the plugin code and produce both a JavaScript source file and a type definition file.插件现已完成,你可以[发布到 npm]或在本地使用它。
¥With the plugin now complete you can [publish to npm] or use it locally.
你无需将插件发布到 npm 即可使用它。你可以将其包含在 Fastify 项目中并像引用任何代码一样引用它!作为 TypeScript 用户,请确保声明覆盖存在于将包含在项目编译中的某个地方,以便 TypeScript 解释器可以处理它。
¥You do not need to publish your plugin to npm to use it. You can include it in a Fastify project and reference it as you would any piece of code! As a TypeScript user, make sure the declaration override exists somewhere that will be included in your project compilation so the TypeScript interpreter can process it.
为 Fastify 插件创建类型定义
¥Creating Type Definitions for a Fastify Plugin
本插件指南适用于用 JavaScript 编写的 Fastify 插件。本示例中概述的步骤是为使用你的插件的用户添加 TypeScript 支持。
¥This plugin guide is for Fastify plugins written in JavaScript. The steps outlined in this example are for adding TypeScript support for users consuming your plugin.
初始化一个新的 npm 项目并安装所需的依赖
¥Initialize a new npm project and install required dependencies
npm init -y
npm i fastify-plugin创建两个文件
index.js
和index.d.ts
¥Create two files
index.js
andindex.d.ts
修改包 json 以在
main
和types
属性下包含这些文件(名称不必明确为index
,但建议文件具有相同的名称):¥Modify the package json to include these files under the
main
andtypes
properties (the name does not have to beindex
explicitly, but it is recommended the files have the same name):{
"main": "index.js",
"types": "index.d.ts"
}打开
index.js
并添加以下代码:¥Open
index.js
and add the following code:// fastify-plugin is highly recommended for any plugin you write
const fp = require('fastify-plugin')
function myPlugin (instance, options, done) {
// decorate the fastify instance with a custom function called myPluginFunc
instance.decorate('myPluginFunc', (input) => {
return input.toUpperCase()
})
done()
}
module.exports = fp(myPlugin, {
fastify: '5.x',
name: 'my-plugin' // this is used by fastify-plugin to derive the property name
})打开
index.d.ts
并添加以下代码:¥Open
index.d.ts
and add the following code:import { FastifyPluginCallback } from 'fastify'
interface PluginOptions {
//...
}
// Optionally, you can add any additional exports.
// Here we are exporting the decorator we added.
export interface myPluginFunc {
(input: string): string
}
// Most importantly, use declaration merging to add the custom property to the Fastify type system
declare module 'fastify' {
interface FastifyInstance {
myPluginFunc: myPluginFunc
}
}
// fastify-plugin automatically adds named export, so be sure to add also this type
// the variable name is derived from `options.name` property if `module.exports.myPlugin` is missing
export const myPlugin: FastifyPluginCallback<PluginOptions>
// fastify-plugin automatically adds `.default` property to the exported plugin. See the note below
export default myPlugin
注意:fastify-plugin v2.3.0 及更新版本,自动将 .default
属性和命名导出添加到导出的插件。请确保在你的输入中使用 export default
和 export const myPlugin
,以提供最佳的开发者体验。有关完整示例,你可以查看 @fastify/swagger。
¥Note: fastify-plugin v2.3.0 and
newer, automatically adds .default
property and a named export to the exported
plugin. Be sure to export default
and export const myPlugin
in your typings
to provide the best developer experience. For a complete example you can check
out
@fastify/swagger.
完成这些文件后,该插件现在就可以被任何 TypeScript 项目使用了!
¥With those files completed, the plugin is now ready to be consumed by any TypeScript project!
Fastify 插件系统使开发者能够装饰 Fastify 实例和请求/响应实例。有关更多信息,请查看 声明合并和通用继承 上的这篇博客文章。
¥The Fastify plugin system enables developers to decorate the Fastify instance, and the request/reply instances. For more information check out this blog post on Declaration Merging and Generic Inheritance.
使用插件
¥Using a Plugin
在 TypeScript 中使用 Fastify 插件就像在 JavaScript 中使用插件一样简单。使用 import/from
导入插件,你就一切就绪了 - 但有一个例外用户应该注意。
¥Using a Fastify plugin in TypeScript is just as easy as using one in JavaScript.
Import the plugin with import/from
and you're all set -- except there is one
exception users should be aware of.
Fastify 插件使用声明合并来修改现有的 Fastify 类型接口(查看前两个示例以了解更多详细信息)。声明合并不是很智能,这意味着如果插件的插件类型定义在 TypeScript 解释器的范围内,那么无论是否使用该插件,都将包含插件类型。这是使用 TypeScript 的一个不幸的限制,并且目前是不可避免的。
¥Fastify plugins use declaration merging to modify existing Fastify type interfaces (check out the previous two examples for more details). Declaration merging is not very smart, meaning if the plugin type definition for a plugin is within the scope of the TypeScript interpreter, then the plugin types will be included regardless of if the plugin is being used or not. This is an unfortunate limitation of using TypeScript and is unavoidable as of right now.
不过,有一些建议可以帮助改善这种体验:
¥However, there are a couple of suggestions to help improve this experience:
确保在 ESLint 中启用了
no-unused-vars
规则,并且任何导入的插件都实际正在加载。¥Make sure the
no-unused-vars
rule is enabled in ESLint and any imported plugin are actually being loaded.如果你已启用
@typescript-eslint/no-floating-promises
,请仔细检查你的 ESLint 配置是否包含allowForKnownSafePromises
属性,如typescript-eslint no-floating-promises allowForKnownSafePromises documentation
中所述:¥In case you've the
@typescript-eslint/no-floating-promises
enabled, please double-check that your ESLint configuration includes aallowForKnownSafePromises
property as described on thetypescript-eslint no-floating-promises allowForKnownSafePromises documentation
:
{
"rules": {
"@typescript-eslint/no-floating-promises": ["error", {
"allowForKnownSafePromises": [
{ "from": "package", "name": "FastifyInstance", "package": "fastify" },
{ "from": "package", "name": "FastifyReply", "package": "fastify" },
{ "from": "package", "name": "SafePromiseLike", "package": "fastify" },
]
}]
}
}
使用 depcheck 或 npm-check 等模块来验证插件依赖是否正在项目中的某个地方使用。
¥Use a module such as depcheck or npm-check to verify plugin dependencies are being used somewhere in your project.
请注意,使用 require
将无法正确加载类型定义,并可能导致类型错误。TypeScript 只能识别直接导入到代码中的类型,这意味着你可以使用 require inline 和 import on top。例如:
¥Note that using require
will not load the type definitions properly and may
cause type errors.
TypeScript can only identify the types that are directly imported into code,
which means that you can use require inline with import on top. For example:
import 'plugin' // here will trigger the type augmentation.
fastify.register(require('plugin'))
import plugin from 'plugin' // here will trigger the type augmentation.
fastify.register(plugin)
或者甚至在 tsconfig 上进行显式配置
¥Or even explicit config on tsconfig
{
"types": ["plugin"] // we force TypeScript to import the types
}
Vanilla JavaScript 中的代码完成
¥Code Completion In Vanilla JavaScript
Vanilla JavaScript 可以使用已发布的类型通过遵循 TypeScript JSDoc 参考 来提供代码完成(例如 Intellisense)。
¥Vanilla JavaScript can use the published types to provide code completion (e.g. Intellisense) by following the TypeScript JSDoc Reference.
例如:
¥For example:
/** @type {import('fastify').FastifyPluginAsync<{ optionA: boolean, optionB: string }>} */
module.exports = async function (fastify, { optionA, optionB }) {
fastify.get('/look', () => 'at me');
}
API 类型系统文档
¥API Type System Documentation
本节详细介绍了 Fastify 3.x 版本中所有可用的类型
¥This section is a detailed account of all the types available to you in Fastify version 3.x
所有 http
、https
和 http2
类型都是从 @types/node
推断出来的
¥All http
, https
, and http2
types are inferred from @types/node
泛型 由其默认值及其约束值记录。阅读这些文章以获取有关 TypeScript 泛型的更多信息。
¥Generics are documented by their default value as well as their constraint value(s). Read these articles for more information on TypeScript generics.
如何导入
¥How to import
Fastify API 由 fastify()
方法提供支持。在 JavaScript 中,你可以使用 const fastify = require('fastify')
导入它。在 TypeScript 中,建议改用 import/from
语法,以便可以解析类型。Fastify 类型系统支持多种导入方法。
¥The Fastify API is powered by the fastify()
method. In JavaScript you would
import it using const fastify = require('fastify')
. In TypeScript it is
recommended to use the import/from
syntax instead so types can be resolved.
There are a couple supported import methods with the Fastify type system.
import fastify from 'fastify'
类型已解析,但无法使用点表示法访问
¥Types are resolved but not accessible using dot notation
示例:
¥Example:
import fastify from 'fastify'
const f = fastify()
f.listen({ port: 8080 }, () => { console.log('running') })通过解构访问类型:
¥Gain access to types with destructuring:
import fastify, { FastifyInstance } from 'fastify'
const f: FastifyInstance = fastify()
f.listen({ port: 8080 }, () => { console.log('running') })解构也适用于主要的 API 方法:
¥Destructuring also works for the main API method:
import { fastify, FastifyInstance } from 'fastify'
const f: FastifyInstance = fastify()
f.listen({ port: 8080 }, () => { console.log('running') })
import * as Fastify from 'fastify'
使用点表示法解析和访问类型
¥Types are resolved and accessible using dot notation
调用主要 Fastify API 方法需要稍微不同的语法(参见示例)
¥Calling the main Fastify API method requires a slightly different syntax (see example)
示例:
¥Example:
import * as Fastify from 'fastify'
const f: Fastify.FastifyInstance = Fastify.fastify()
f.listen({ port: 8080 }, () => { console.log('running') })
const fastify = require('fastify')
此语法有效,并将按预期导入 fastify;但是,类型不会被解析
¥This syntax is valid and will import fastify as expected; however, types will not be resolved
示例:
¥Example:
const fastify = require('fastify')
const f = fastify()
f.listen({ port: 8080 }, () => { console.log('running') })支持解构并将正确解析类型
¥Destructuring is supported and will resolve types properly
const { fastify } = require('fastify')
const f = fastify()
f.listen({ port: 8080 }, () => { console.log('running') })
泛型
¥Generics
许多类型定义共享相同的通用参数;它们都在本节中详细记录。
¥Many type definitions share the same generic parameters; they are all documented, in detail, within this section.
大多数定义依赖于 @types/node
模块 http
、https
和 http2
¥Most definitions depend on @types/node
modules http
, https
, and http2
RawServer
底层 Node.js 服务器类型
¥Underlying Node.js server type
默认:http.Server
¥Default: http.Server
限制条件:http.Server
, https.Server
, http2.Http2Server
, http2.Http2SecureServer
¥Constraints: http.Server
, https.Server
, http2.Http2Server
,
http2.Http2SecureServer
强制通用参数:RawRequest
, RawReply
¥Enforces generic parameters: RawRequest
,
RawReply
RawRequest
底层 Node.js 请求类型
¥Underlying Node.js request type
默认:RawRequestDefaultExpression
¥Default: RawRequestDefaultExpression
限制条件:http.IncomingMessage
, http2.Http2ServerRequest
¥Constraints: http.IncomingMessage
, http2.Http2ServerRequest
执行者:RawServer
¥Enforced by: RawServer
RawReply
底层 Node.js 响应类型
¥Underlying Node.js response type
¥Default: RawReplyDefaultExpression
限制条件:http.ServerResponse
, http2.Http2ServerResponse
¥Constraints: http.ServerResponse
, http2.Http2ServerResponse
执行者:RawServer
¥Enforced by: RawServer
Logger
Fastify 日志实用程序
¥Fastify logging utility
¥Default: FastifyLoggerOptions
执行者:RawServer
¥Enforced by: RawServer
RawBody
内容类型解析器方法的通用参数。
¥A generic parameter for the content-type-parser methods.
限制条件:string | Buffer
¥Constraints: string | Buffer
Fastify
fastify< RawRequest, RawReply, Logger>(opts?: FastifyServerOptions): FastifyInstance
主要的 Fastify API 方法。默认情况下创建一个 HTTP 服务器。利用判别联合和重载方法,类型系统将根据基于方法的选项自动推断正在创建哪种类型的服务器(http、https 或 http2)(有关更多信息,请参阅下面的示例)。它还支持广泛的通用类型系统,允许用户扩展底层 Node.js 服务器、请求和回复对象。此外,Logger
泛型适用于自定义日志类型。有关更多信息,请参阅下面的示例和通用细分。
¥The main Fastify API method. By default creates an HTTP server. Utilizing
discriminant unions and overload methods, the type system will automatically
infer which type of server (http, https, or http2) is being created purely based
on the options based to the method (see the examples below for more
information). It also supports an extensive generic type system to allow the
user to extend the underlying Node.js Server, Request, and Reply objects.
Additionally, the Logger
generic exists for custom log types. See the examples
and generic breakdown below for more information.
示例 1:标准 HTTP 服务器
¥Example 1: Standard HTTP server
无需指定 Server
泛型,因为类型系统默认为 HTTP。
¥No need to specify the Server
generic as the type system defaults to HTTP.
import fastify from 'fastify'
const server = fastify()
查看通过示例学习 - 入门 示例,用于更详细的 http 服务器演练。
¥Check out the Learn By Example - Getting Started example for a more detailed http server walkthrough.
示例 2:HTTPS 服务器
¥Example 2: HTTPS server
从
@types/node
和fastify
创建以下导入¥Create the following imports from
@types/node
andfastify
import fs from 'fs'
import path from 'path'
import fastify from 'fastify'在设置 Fastify HTTPS 服务器以创建
key.pem
和cert.pem
文件之前,请执行以下步骤:¥Perform the following steps before setting up a Fastify HTTPS server to create the
key.pem
andcert.pem
files:
openssl genrsa -out key.pem
openssl req -new -key key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem
rm csr.pem
实例化 Fastify https 服务器并添加路由:
¥Instantiate a Fastify https server and add a route:
const server = fastify({
https: {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem'))
}
})
server.get('/', async function (request, reply) {
return { hello: 'world' }
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(0)
}
console.log(`Server listening at ${address}`)
})构建并运行!通过以下查询测试你的服务器:
curl -k https://localhost:8080
¥Build and run! Test your server out by querying with:
curl -k https://localhost:8080
示例 3:HTTP2 服务器
¥Example 3: HTTP2 server
有两种类型的 HTTP2 服务器类型,不安全和安全。两者都需要在 options
对象中将 http2
属性指定为 true
。https
属性用于创建安全的 http2 服务器;省略 https
属性将创建一个不安全的 http2 服务器。
¥There are two types of HTTP2 server types, insecure and secure. Both require
specifying the http2
property as true
in the options
object. The https
property is used for creating a secure http2 server; omitting the https
property will create an insecure http2 server.
const insecureServer = fastify({ http2: true })
const secureServer = fastify({
http2: true,
https: {} // use the `key.pem` and `cert.pem` files from the https section
})
有关使用 HTTP2 的更多详细信息,请查看 Fastify HTTP2 文档页面。
¥For more details on using HTTP2 check out the Fastify HTTP2 documentation page.
示例 4:扩展 HTTP 服务器
¥Example 4: Extended HTTP server
你不仅可以指定服务器类型,还可以指定请求和回复类型。因此,你可以指定特殊属性、方法等!在服务器实例化时指定时,自定义类型将在自定义类型的所有其他实例上可用。
¥Not only can you specify the server type, but also the request and reply types. Thus, allowing you to specify special properties, methods, and more! When specified at server instantiation, the custom type becomes available on all further instances of the custom type.
import fastify from 'fastify'
import http from 'http'
interface customRequest extends http.IncomingMessage {
mySpecialProp: string
}
const server = fastifyhttp.Server, customRequest()
server.get('/', async (request, reply) => {
const someValue = request.raw.mySpecialProp // TS knows this is a string, because of the `customRequest` interface
return someValue.toUpperCase()
})
示例 5:指定日志器类型
¥Example 5: Specifying logger types
Fastify 在后台使用 Pino 日志库。由于 pino@7
,在构造 Fastify 实例时,可以通过 logger
字段配置其所有属性。如果你需要的属性未公开,请向 Pino
打开一个问题或通过同一字段将预配置的 Pino 外部实例(或任何其他兼容日志器)作为临时修复传递给 Fastify。这也允许创建自定义序列化器,有关更多信息,请参阅 日志 文档。
¥Fastify uses Pino logging library under the hood. Since
pino@7
, all of it's properties can be configured via logger
field when
constructing Fastify's instance. If properties you need aren't exposed, please
open an Issue to Pino
or pass a
preconfigured external instance of Pino (or any other compatible logger) as
temporary fix to Fastify via the same field. This allows creating custom
serializers as well, see the Logging documentation for more info.
import fastify from 'fastify'
const server = fastify({
logger: {
level: 'info',
redact: ['x-userinfo'],
messageKey: 'message'
}
})
server.get('/', async (request, reply) => {
server.log.info('log message')
return 'another message'
})
fastify.HTTPMethods
联盟类型:'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' | 'OPTIONS'
¥Union type of: 'DELETE' | 'GET' | 'HEAD' | 'PATCH' | 'POST' | 'PUT' |
'OPTIONS'
fastify.RawServerBase
依赖于 @types/node
模块 http
、https
、http2
¥Dependent on @types/node
modules http
, https
, http2
联盟类型:http.Server | https.Server | http2.Http2Server | http2.Http2SecureServer
¥Union type of: http.Server | https.Server | http2.Http2Server |
http2.Http2SecureServer
fastify.RawServerDefault
依赖于 @types/node
模块 http
¥Dependent on @types/node
modules http
http.Server
的类型别名
¥Type alias for http.Server
fastify.FastifyServerOptions< RawServer, Logger>
Fastify 服务器实例化中使用的属性接口。用于主 fastify()
方法。RawServer
和 Logger
通用参数通过该方法传递。
¥An interface of properties used in the instantiation of the Fastify server. Is
used in the main fastify()
method. The RawServer
and Logger
generic parameters are passed down through that method.
有关使用 TypeScript 实例化 Fastify 服务器的示例,请参阅主要 fastify 方法类型定义部分。
¥See the main fastify method type definition section for examples on instantiating a Fastify server with TypeScript.
fastify.FastifyInstance< RawServer, RawRequest, RequestGeneric, Logger>
表示 Fastify 服务器对象的接口。这是从 fastify()
方法返回的服务器实例。此类型是一个接口,因此如果你的代码使用 decorate
方法,则可以通过 声明合并 进行扩展。
¥Interface that represents the Fastify server object. This is the returned server
instance from the fastify()
method. This type is an interface so it
can be extended via declaration
merging
if your code makes use of the decorate
method.
通过使用通用级联,附加到实例的所有方法都从实例化继承通用属性。这意味着通过指定服务器、请求或响应类型,所有方法都将知道如何键入这些对象。
¥Through the use of generic cascading, all methods attached to the instance inherit the generic properties from instantiation. This means that by specifying the server, request, or reply types, all methods will know how to type those objects.
查看主要 通过实例学习 部分以获取详细指南,或查看更简化的 fastify 方法示例以获取有关此接口的更多详细信息。
¥Check out the main Learn by Example section for detailed guides, or the more simplified fastify method examples for additional details on this interface.
请求
¥Request
fastify.FastifyRequest< RequestGeneric, RawServer, RawRequest>
该接口包含 Fastify 请求对象的属性。这里添加的属性不考虑请求对象的类型(http vs http2),也不考虑它所服务的路由级别;因此,在 GET 请求中调用 request.body
不会引发错误(但祝你好运发送带有正文的 GET 请求😉)。
¥This interface contains properties of Fastify request object. The properties
added here disregard what kind of request object (http vs http2) and disregard
what route level it is serving; thus calling request.body
inside a GET request
will not throw an error (but good luck sending a GET request with a body 😉).
如果你需要向 FastifyRequest
对象添加自定义属性(例如使用 [decorateRequest
][DecorateRequest] 方法时),则需要在此接口上使用声明合并。
¥If you need to add custom properties to the FastifyRequest
object (such as
when using the [decorateRequest
][DecorateRequest] method) you need to use
declaration merging on this interface.
FastifyRequest
部分提供了一个基本示例。有关更详细的示例,请查看“通过示例学习”部分:插件
¥A basic example is provided in the FastifyRequest
section.
For a more detailed example check out the Learn By Example section:
Plugins
示例
¥Example
import fastify from 'fastify'
const server = fastify()
server.decorateRequest('someProp', 'hello!')
server.get('/', async (request, reply) => {
const { someProp } = request // need to use declaration merging to add this prop to the request interface
return someProp
})
// this declaration must be in scope of the typescript interpreter to work
declare module 'fastify' {
interface FastifyRequest { // you must reference the interface and not the type
someProp: string
}
}
// Or you can type your request using
type CustomRequest = FastifyRequest<{
Body: { test: boolean };
}>
server.get('/typedRequest', async (request: CustomRequest, reply: FastifyReply) => {
return request.body.test
})
fastify.RequestGenericInterface
Fastify 请求对象有四个动态属性:body
、params
、query
和 headers
。它们各自的类型可以通过该接口进行分配。它是一个命名属性接口,使开发者能够忽略他们不想指定的属性。所有省略的属性都默认为 unknown
。对应的属性名称为:Body
, Querystring
, Params
, Headers
.
¥Fastify request objects have four dynamic properties: body
, params
, query
,
and headers
. Their respective types are assignable through this interface. It
is a named property interface enabling the developer to ignore the properties
they do not want to specify. All omitted properties are defaulted to unknown
.
The corresponding property names are: Body
, Querystring
, Params
,
Headers
.
import fastify, { RequestGenericInterface } from 'fastify'
const server = fastify()
interface requestGeneric extends RequestGenericInterface {
Querystring: {
name: string
}
}
server.get<requestGeneric>('/', async (request, reply) => {
const { name } = request.query // the name prop now exists on the query prop
return name.toUpperCase()
})
如果你想查看使用此界面的详细示例,请查看“通过示例学习”部分:JSON 结构。
¥If you want to see a detailed example of using this interface check out the Learn by Example section: JSON Schema.
fastify.RawRequestDefaultExpression\<RawServer>
依赖于 @types/node
模块 http
、https
、http2
¥Dependent on @types/node
modules http
, https
, http2
通用参数 RawServer
默认为 RawServerDefault
¥Generic parameter RawServer
defaults to RawServerDefault
如果 RawServer
是 http.Server
或 https.Server
类型,则此表达式返回 http.IncomingMessage
,否则返回 http2.Http2ServerRequest
。
¥If RawServer
is of type http.Server
or https.Server
, then this expression
returns http.IncomingMessage
, otherwise, it returns
http2.Http2ServerRequest
.
import http from 'http'
import http2 from 'http2'
import { RawRequestDefaultExpression } from 'fastify'
RawRequestDefaultExpressionhttp.Server // -> http.IncomingMessage
RawRequestDefaultExpressionhttp2.Http2Server // -> http2.Http2ServerRequest
响应
¥Reply
fastify.FastifyReply<RequestGeneric, RawServer, RawRequest, RawReply, ContextConfig>
该接口包含 Fastify 添加到标准 Node.js 响应对象的自定义属性。此处添加的属性不考虑响应对象的类型(http 与 http2)。
¥This interface contains the custom properties that Fastify adds to the standard Node.js reply object. The properties added here disregard what kind of reply object (http vs http2).
如果你需要向 FastifyReply 对象添加自定义属性(例如使用 decorateReply
方法时),则需要在此接口上使用声明合并。
¥If you need to add custom properties to the FastifyReply object (such as when
using the decorateReply
method) you need to use declaration merging on this
interface.
FastifyReply
部分提供了一个基本示例。有关更详细的示例,请查看“通过示例学习”部分:插件
¥A basic example is provided in the FastifyReply
section. For a
more detailed example check out the Learn By Example section:
Plugins
示例
¥Example
import fastify from 'fastify'
const server = fastify()
server.decorateReply('someProp', 'world')
server.get('/', async (request, reply) => {
const { someProp } = reply // need to use declaration merging to add this prop to the reply interface
return someProp
})
// this declaration must be in scope of the typescript interpreter to work
declare module 'fastify' {
interface FastifyReply { // you must reference the interface and not the type
someProp: string
}
}
fastify.RawReplyDefaultExpression< RawServer>
依赖于 @types/node
模块 http
、https
、http2
¥Dependent on @types/node
modules http
, https
, http2
通用参数 RawServer
默认为 RawServerDefault
¥Generic parameter RawServer
defaults to RawServerDefault
如果 RawServer
是 http.Server
或 https.Server
类型,则此表达式返回 http.ServerResponse
,否则返回 http2.Http2ServerResponse
。
¥If RawServer
is of type http.Server
or https.Server
, then this expression
returns http.ServerResponse
, otherwise, it returns
http2.Http2ServerResponse
.
import http from 'http'
import http2 from 'http2'
import { RawReplyDefaultExpression } from 'fastify'
RawReplyDefaultExpressionhttp.Server // -> http.ServerResponse
RawReplyDefaultExpressionhttp2.Http2Server // -> http2.Http2ServerResponse
Plugin
Fastify 允许用户通过插件扩展其功能。插件可以是一组路由、服务器装饰器或其他任何东西。要激活插件,请使用 fastify.register()
方法。
¥Fastify allows the user to extend its functionalities with plugins. A plugin can
be a set of routes, a server decorator or whatever. To activate plugins, use the
fastify.register()
method.
为 Fastify 创建插件时,建议使用 fastify-plugin
模块。此外,在通过示例学习,插件 部分中提供了使用 TypeScript 和 Fastify 创建插件的指南。
¥When creating plugins for Fastify, it is recommended to use the fastify-plugin
module. Additionally, there is a guide to creating plugins with TypeScript and
Fastify available in the Learn by Example, Plugins section.
fastify.FastifyPluginCallback< Options>
fastify.register()
方法中使用的接口方法定义。
¥Interface method definition used within the
fastify.register()
method.
fastify.FastifyPluginAsync< Options>
fastify.register()
方法中使用的接口方法定义。
¥Interface method definition used within the
fastify.register()
method.
fastify.FastifyPlugin< Options>
fastify.register()
方法中使用的接口方法定义。文档已弃用,转而使用 FastifyPluginCallback
和 FastifyPluginAsync
,因为通用 FastifyPlugin
无法正确推断异步函数的类型。
¥Interface method definition used within the
fastify.register()
method. Document deprecated in favor of
FastifyPluginCallback
and FastifyPluginAsync
since general FastifyPlugin
doesn't properly infer types for async functions.
fastify.FastifyPluginOptions
用于将 fastify.register()
的 options
参数约束为对象的松散类型对象。创建插件时,将其选项定义为此接口(interface MyPluginOptions extends FastifyPluginOptions
)的扩展,以便可以将它们传递给注册方法。
¥A loosely typed object used to constrain the options
parameter of
fastify.register()
to an object. When creating a plugin,
define its options as an extension of this interface (interface MyPluginOptions
extends FastifyPluginOptions
) so they can be passed to the register method.
注册
¥Register
fastify.FastifyRegister(plugin: [FastifyPluginCallback][FastifyPluginCallback], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
fastify.FastifyRegister(plugin: [FastifyPluginAsync][FastifyPluginAsync], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
fastify.FastifyRegister(plugin: [FastifyPlugin][FastifyPlugin], opts: [FastifyRegisterOptions][FastifyRegisterOptions])
此类型接口指定 fastify.register()
方法的类型。类型接口返回一个函数签名,其底层通用 Options
默认为 FastifyPluginOptions。它在调用此函数时从 FastifyPlugin 参数推断出此泛型,因此无需指定底层泛型。options 参数是插件选项和两个附加可选属性的交集:prefix: string
和 logLevel
:LogLevel。FastifyPlugin
已弃用,请改用 FastifyPluginCallback
和 FastifyPluginAsync
。
¥This type interface specifies the type for the
fastify.register()
method. The type interface returns
a function signature with an underlying generic Options
which is defaulted to
FastifyPluginOptions. It infers this generic from the
FastifyPlugin parameter when calling this function so there is no need to
specify the underlying generic. The options parameter is the intersection of the
plugin's options and two additional optional properties: prefix: string
and
logLevel
: LogLevel. FastifyPlugin
is deprecated use
FastifyPluginCallback
and FastifyPluginAsync
instead.
下面是选项推断的示例:
¥Below is an example of the options inference in action:
const server = fastify()
const plugin: FastifyPluginCallback<{
option1: string;
option2: boolean;
}> = function (instance, opts, done) { }
server().register(plugin, {}) // Error - options object is missing required properties
server().register(plugin, { option1: '', option2: true }) // OK - options object contains required properties
有关在 Fastify 中创建 TypeScript 插件的更多详细示例,请参阅通过示例学习,插件 部分。
¥See the Learn By Example, Plugins section for more detailed examples of creating TypeScript plugins in Fastify.
fastify.FastifyRegisterOptions
此类型是 Options
通用和非导出接口 RegisterOptions
的交集,它指定了两个可选属性:prefix: string
和 logLevel
:LogLevel。该类型还可以指定为返回前面描述的交集的函数。
¥This type is the intersection of the Options
generic and a non-exported
interface RegisterOptions
that specifies two optional properties: prefix:
string
and logLevel
: LogLevel. This type can also be specified as
a function that returns the previously described intersection.
Logger
查看 指定日志器类型 示例以获取有关指定自定义日志器的更多详细信息。
¥Check out the Specifying Logger Types example for more details on specifying a custom logger.
fastify.FastifyLoggerOptions< RawServer, RawRequest, RawReply>
内部 Fastify 日志器的接口定义。它模拟了 Pino.js 日志器。当通过服务器选项启用时,请按照常规 logger 文档使用它。
¥An interface definition for the internal Fastify logger. It is emulative of the Pino.js logger. When enabled through server options, use it following the general logger documentation.
fastify.FastifyLogFn
一个重载函数接口,实现 Fastify 调用日志方法的两种方式。该接口被传递到 FastifyLoggerOptions 对象上的所有关联日志级别属性。
¥An overload function interface that implements the two ways Fastify calls log methods. This interface is passed to all associated log level properties on the FastifyLoggerOptions object.
fastify.LogLevel
联盟类型:'info' | 'error' | 'debug' | 'fatal' | 'warn' | 'trace'
¥Union type of: 'info' | 'error' | 'debug' | 'fatal' | 'warn' | 'trace'
Context
上下文类型定义与类型系统的其他高度动态部分类似。路由上下文在路由处理程序方法中可用。
¥The context type definition is similar to the other highly dynamic pieces of the type system. Route context is available in the route handler method.
fastify.FastifyRequestContext
具有单个必需属性 config
的接口,默认情况下设置为 unknown
。可以使用泛型或重载来指定。
¥An interface with a single required property config
that is set by default to
unknown
. Can be specified either using a generic or an overload.
此类型定义可能不完整。如果你正在使用它并且可以提供有关如何改进定义的更多详细信息,我们强烈建议你在主 fastify/fastify 存储库中打开一个问题。提前谢谢你!
¥This type definition is potentially incomplete. If you are using it and can provide more details on how to improve the definition, we strongly encourage you to open an issue in the main fastify/fastify repository. Thank you in advanced!
fastify.FastifyReplyContext
具有单个必需属性 config
的接口,默认情况下设置为 unknown
。可以使用泛型或重载来指定。
¥An interface with a single required property config
that is set by default to
unknown
. Can be specified either using a generic or an overload.
此类型定义可能不完整。如果你正在使用它并且可以提供有关如何改进定义的更多详细信息,我们强烈建议你在主 fastify/fastify 存储库中打开一个问题。提前谢谢你!
¥This type definition is potentially incomplete. If you are using it and can provide more details on how to improve the definition, we strongly encourage you to open an issue in the main fastify/fastify repository. Thank you in advanced!
Routing
Fastify 的核心原则之一是其路由功能。本节中定义的大多数类型均由 Fastify 实例 .route
和 .get/.post/.etc
方法在后台使用。
¥One of the core principles in Fastify is its routing capabilities. Most of the
types defined in this section are used under-the-hood by the Fastify instance
.route
and .get/.post/.etc
methods.
fastify.RouteHandlerMethod< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>
路由处理程序方法的类型声明。有两个参数,request
和 reply
,分别由 FastifyRequest
和 FastifyReply
输入。泛型参数传递给这些实参。对于同步和异步处理程序,该方法分别返回 void
或 Promise<any>
。
¥A type declaration for the route handler methods. Has two arguments, request
and reply
which are typed by FastifyRequest
and FastifyReply
respectively.
The generics parameters are passed through to these arguments. The method
returns either void
or Promise<any>
for synchronous and asynchronous
handlers respectively.
fastify.RouteOptions< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>
扩展 RouteShorthandOptions 并添加以下三个必需属性的接口:
¥An interface that extends RouteShorthandOptions and adds the following three required properties:
method
对应于单个 HTTPMethod 或 HTTPMethods 列表¥
method
which corresponds to a singular HTTPMethod or a list of HTTPMethodsurl
路由字符串¥
url
a string for the routehandler
路由处理程序方法,有关更多详细信息,请参阅 [RouteHandlerMethod][RouteHandlerMethod]¥
handler
the route handler method, see [RouteHandlerMethod][] for more details
fastify.RouteShorthandMethod< RawServer, RawRequest, RawReply>
与 .get/.post/.etc
方法结合使用的三种简写路由方法的重载函数接口。
¥An overloaded function interface for three kinds of shorthand route methods to
be used in conjunction with the .get/.post/.etc
methods.
fastify.RouteShorthandOptions< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>
涵盖路由所有基本选项的界面。该接口上的每个属性都是可选的,并且它充当 RouteOptions 和 RouteShorthandOptionsWithHandler 接口的基础。
¥An interface that covers all of the base options for a route. Each property on this interface is optional, and it serves as the base for the RouteOptions and RouteShorthandOptionsWithHandler interfaces.
fastify.RouteShorthandOptionsWithHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>
此接口向 RouteShorthandOptions 接口 handler
添加一个必需的属性,其类型为 RouteHandlerMethod
¥This interface adds a single, required property to the RouteShorthandOptions
interface handler
which is of type RouteHandlerMethod
Parsers
RawBody
泛型类型,即 string
或 Buffer
¥A generic type that is either a string
or Buffer
fastify.FastifyBodyParser< RawBody, RawServer, RawRequest>
用于指定主体解析器方法的函数类型定义。使用 RawBody
泛型来指定正在解析的主体类型。
¥A function type definition for specifying a body parser method. Use the
RawBody
generic to specify the type of the body being parsed.
fastify.FastifyContentTypeParser< RawServer, RawRequest>
用于指定主体解析器方法的函数类型定义。内容通过 RawRequest
泛型输入。
¥A function type definition for specifying a body parser method. Content is typed
via the RawRequest
generic.
fastify.AddContentTypeParser< RawServer, RawRequest>
addContentTypeParser
方法的重载接口函数定义。如果将 parseAs
传递给 opts
参数,则定义将使用 [FastifyBodyParser][FastifyBodyParser] 作为 parser
参数;否则,它使用 [FastifyContentTypeParser][FastifyContentTypeParser]。
¥An overloaded interface function definition for the addContentTypeParser
method. If parseAs
is passed to the opts
parameter, the definition uses
[FastifyBodyParser][] for the parser
parameter; otherwise, it uses
[FastifyContentTypeParser][].
fastify.hasContentTypeParser
一种检查特定内容类型的类型解析器是否存在的方法
¥A method for checking the existence of a type parser of a certain content type
错误
¥Errors
fastify.FastifyError
FastifyError 是一个自定义错误对象,包含状态代码和验证结果。
¥FastifyError is a custom error object that includes status code and validation results.
它扩展了 Node.js Error
类型,并添加了两个额外的可选属性:statusCode: number
和 validation: ValidationResult[]
。
¥It extends the Node.js Error
type, and adds two additional, optional
properties: statusCode: number
and validation: ValidationResult[]
.
fastify.ValidationResult
路由验证内部依赖于 Ajv,它是一个高性能的 JSON 模式验证器。
¥The route validation internally relies upon Ajv, which is a high-performance JSON schema validator.
该接口被传递给 FastifyError 的实例。
¥This interface is passed to instance of FastifyError.
钩子
¥Hooks
fastify.onRequestHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, done: (err?: FastifyError) => void): Promise\<unknown> | void
onRequest
是在请求生命周期中要执行的第一个钩子。没有前一个钩子,下一个钩子将是 preParsing
。
¥onRequest
is the first hook to be executed in the request lifecycle. There was
no previous hook, the next hook will be preParsing
.
注意:在 onRequest
钩子中,request.body 将始终为空,因为主体解析发生在 preHandler
钩子之前。
¥Notice: in the onRequest
hook, request.body will always be null, because the
body parsing happens before the preHandler
hook.
fastify.preParsingHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, done: (err?: FastifyError) => void): Promise\<unknown> | void
preParsing
是在请求生命周期中要执行的第二个钩子。上一个钩子是 onRequest
,下一个钩子将是 preValidation
。
¥preParsing
is the second hook to be executed in the request lifecycle. The
previous hook was onRequest
, the next hook will be preValidation
.
注意:在 preParsing
钩子中,request.body 将始终为空,因为主体解析发生在 preValidation
钩子之前。
¥Notice: in the preParsing
hook, request.body will always be null, because the
body parsing happens before the preValidation
hook.
注意:你还应该将 receivedEncodedLength
属性添加到返回的流中。此属性用于将请求负载与 Content-Length
标头值正确匹配。理想情况下,应在每个收到的块上更新此属性。
¥Notice: you should also add receivedEncodedLength
property to the returned
stream. This property is used to correctly match the request payload with the
Content-Length
header value. Ideally, this property should be updated on each
received chunk.
fastify.preValidationHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, done: (err?: FastifyError) => void): Promise\<unknown> | void
preValidation
是在请求生命周期中要执行的第三个钩子。上一个钩子是 preParsing
,下一个钩子将是 preHandler
。
¥preValidation
is the third hook to be executed in the request lifecycle. The
previous hook was preParsing
, the next hook will be preHandler
.
fastify.preHandlerHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, done: (err?: FastifyError) => void): Promise\<unknown> | void
preHandler
是在请求生命周期中要执行的第四个钩子。上一个钩子是 preValidation
,下一个钩子将是 preSerialization
。
¥preHandler
is the fourth hook to be executed in the request lifecycle. The
previous hook was preValidation
, the next hook will be preSerialization
.
fastify.preSerializationHookHandler< PreSerializationPayload, RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, payload: PreSerializationPayload, done: (err: FastifyError | null, res?: unknown) => void): Promise\<unknown> | void
preSerialization
是在请求生命周期中要执行的第五个钩子。上一个钩子是 preHandler
,下一个钩子将是 onSend
。
¥preSerialization
is the fifth hook to be executed in the request lifecycle.
The previous hook was preHandler
, the next hook will be onSend
.
注意:如果有效负载是字符串、缓冲区、流或 null,则不会调用钩子。
¥Note: the hook is NOT called if the payload is a string, a Buffer, a stream or null.
fastify.onSendHookHandler< OnSendPayload, RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, payload: OnSendPayload, done: (err: FastifyError | null, res?: unknown) => void): Promise\<unknown> | void
你可以使用 onSend
钩子更改有效负载。它是请求生命周期中要执行的第六个钩子。上一个钩子是 preSerialization
,下一个钩子将是 onResponse
。
¥You can change the payload with the onSend
hook. It is the sixth hook to be
executed in the request lifecycle. The previous hook was preSerialization
, the
next hook will be onResponse
.
注意:如果更改有效负载,则只能将其更改为字符串、缓冲区、流或 null。
¥Note: If you change the payload, you may only change it to a string, a Buffer, a stream, or null.
fastify.onResponseHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, done: (err?: FastifyError) => void): Promise\<unknown> | void
onResponse
是请求钩子生命周期中的第七个也是最后一个钩子。上一个钩子是 onSend
,没有下一个钩子。
¥onResponse
is the seventh and last hook in the request hook lifecycle. The
previous hook was onSend
, there is no next hook.
onResponse 钩子在发送响应后执行,因此你将无法向客户端发送更多数据。然而,它对于将数据发送到外部服务很有用,例如收集统计数据。
¥The onResponse hook is executed when a response has been sent, so you will not be able to send more data to the client. It can however be useful for sending data to external services, for example to gather statistics.
fastify.onErrorHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(request: FastifyRequest, reply: FastifyReply, error: FastifyError, done: () => void): Promise\<unknown> | void
如果你需要执行一些自定义错误日志记录或添加一些特定标头以防出现错误,则此钩子非常有用。
¥This hook is useful if you need to do some custom error logging or add some specific header in case of error.
它不是为了改变错误,调用 reply.send 会抛出异常。
¥It is not intended for changing the error, and calling reply.send will throw an exception.
仅当执行了 customErrorHandler 后,并且仅当 customErrorHandler 将错误发送回用户时,才会执行此钩子(请注意,默认的 customErrorHandler 始终将错误发送回用户)。
¥This hook will be executed only after the customErrorHandler has been executed, and only if the customErrorHandler sends an error back to the user (Note that the default customErrorHandler always sends the error back to the user).
注意:与其他钩子不同,不支持将错误传递给完成函数。
¥Notice: unlike the other hooks, pass an error to the done function is not supported.
fastify.onRouteHookHandler< RawServer, RawRequest, RawReply, RequestGeneric, ContextConfig>(opts: RouteOptions & { path: string; prefix: string }): Promise\<unknown> | void
注册新路由时触发。监听器将传递一个 routeOptions 对象作为唯一参数。该接口是同步的,因此,监听器不会传递回调
¥Triggered when a new route is registered. Listeners are passed a routeOptions object as the sole parameter. The interface is synchronous, and, as such, the listener does not get passed a callback
fastify.onRegisterHookHandler< RawServer, RawRequest, RawReply, Logger>(instance: FastifyInstance, done: (err?: FastifyError) => void): Promise\<unknown> | void
当注册新插件并创建新封装上下文时触发。该钩子将在注册代码之前执行。
¥Triggered when a new plugin is registered and a new encapsulation context is created. The hook will be executed before the registered code.
如果你正在开发一个插件,需要知道插件上下文何时形成,并且你希望在该特定上下文中进行操作,则此钩子可能会很有用。
¥This hook can be useful if you are developing a plugin that needs to know when a plugin context is formed, and you want to operate in that specific context.
注意:如果插件包含在 fastify-plugin 中,则不会调用此钩子。
¥Note: This hook will not be called if a plugin is wrapped inside fastify-plugin.
fastify.onCloseHookHandler< RawServer, RawRequest, RawReply, Logger>(instance: FastifyInstance, done: (err?: FastifyError) => void): Promise\<unknown> | void
当调用 fastify.close() 来停止服务器时触发。当插件需要 "shutdown" 事件时,它很有用,例如,关闭与数据库的打开连接。
¥Triggered when fastify.close() is invoked to stop the server. It is useful when plugins need a "shutdown" event, for example to close an open connection to a database.