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'));