Fastify
Fastify 是一个高性能的 Node.js Web 框架,专注于提供最好的开发体验和极致的性能。它的主要特点是快速的路由查找算法和插件架构,使其成为构建高性能 Web 应用的理想选择。
1. 基础使用
1.1 安装和设置
# 创建新项目
mkdir fastify-app
cd fastify-app
npm init -y
# 安装 Fastify
npm install fastify
# 安装常用插件
npm install @fastify/cors @fastify/swagger @fastify/jwt @fastify/static
1.2 基本应用
// app.js
const fastify = require('fastify')({
logger: true
});
// 声明路由
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
// 启动服务器
const start = async () => {
try {
await fastify.listen({ port: 3000 });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();
2. 路由系统
2.1 基础路由
// routes/users.js
async function routes(fastify, options) {
// GET /users
fastify.get('/users', async (request, reply) => {
return [{ id: 1, name: 'John' }];
});
// GET /users/:id
fastify.get('/users/:id', {
schema: {
params: {
type: 'object',
properties: {
id: { type: 'string' }
}
}
}
}, async (request, reply) => {
const { id } = request.params;
return { id, name: 'John' };
});
// POST /users
fastify.post('/users', {
schema: {
body: {
type: 'object',
required: ['name', 'email'],
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' }
}
}
}
}, async (request, reply) => {
const user = request.body;
reply.code(201);
return user;
});
}
module.exports = routes;
// app.js
fastify.register(require('./routes/users'));
2.2 路由选项和钩子
fastify.route({
method: 'GET',
url: '/custom',
schema: {
querystring: {
name: { type: 'string' },
age: { type: 'integer' }
},
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
},
preHandler: async (request, reply) => {
// 前置处理器
},
handler: async (request, reply) => {
return { hello: 'world' };
}
});
// 路由钩子
fastify.addHook('onRequest', async (request, reply) => {
// 请求开始时执行
});
fastify.addHook('preHandler', async (request, reply) => {
// 处理请求前执行
});
fastify.addHook('onResponse', async (request, reply) => {
// 响应发送后执行
});
3. 插件系统
3.1 创建插件
// plugins/db.js
const fp = require('fastify-plugin');
const mongoose = require('mongoose');
async function dbConnector(fastify, options) {
const url = options.url || 'mongodb://localhost/fastify-app';
mongoose.connect(url);
fastify.decorate('mongo', mongoose);
}
module.exports = fp(dbConnector);
// 使用插件
fastify.register(require('./plugins/db'), {
url: 'mongodb://localhost/fastify-app'
});
3.2 常用插件
const fastify = require('fastify')();
// CORS
await fastify.register(require('@fastify/cors'), {
origin: true
});
// 静态文件
await fastify.register(require('@fastify/static'), {
root: path.join(__dirname, 'public')
});
// Swagger
await fastify.register(require('@fastify/swagger'), {
routePrefix: '/documentation',
swagger: {
info: {
title: 'Fastify API',
description: 'API documentation',
version: '1.0.0'
}
},
exposeRoute: true
});
// JWT
await fastify.register(require('@fastify/jwt'), {
secret: 'your-secret-key'
});
4. 验证和序列化
4.1 请求验证
const schema = {
body: {
type: 'object',
required: ['name', 'email'],
properties: {
name: { type: 'string' },
email: { type: 'string', format: 'email' },
age: { type: 'integer', minimum: 0 }
},
additionalProperties: false
},
querystring: {
type: 'object',
properties: {
limit: { type: 'integer', default: 10 },
offset: { type: 'integer', default: 0 }
}
},
params: {
type: 'object',
properties: {
id: { type: 'string', pattern: '^[0-9a-fA-F]{24}$' }
}
},
response: {
200: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' }
}
}
}
};
fastify.post('/users/:id', { schema }, async function (request, reply) {
// 请求已经被验证
const { id } = request.params;
const user = request.body;
return { id, ...user };
});
4.2 序列化
const schema = {
response: {
200: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' },
email: { type: 'string' }
}
}
}
};
fastify.get('/users/:id', {
schema,
serializerCompiler: ({ schema }) => {
return data => JSON.stringify(data);
}
}, async function (request, reply) {
return { id: '1', name: 'John', email: 'john@example.com' };
});