110 lines
2.8 KiB
Markdown
110 lines
2.8 KiB
Markdown
# 4.1-fasify+ts 项目
|
|
|
|
## 初始化
|
|
|
|
```sh
|
|
pnpm init
|
|
pnpm add -D typescript
|
|
|
|
# 生成一个 tsconfig.json 文件
|
|
npx tsc --init
|
|
```
|
|
|
|
`tsconfig.json` 需要进行一些调整
|
|
|
|
```json
|
|
{
|
|
"compilerOptions": {
|
|
"target": "es2022", // 根据 Node.js 版本选择合适的 ECMAScript 目标版本
|
|
"module": "node16", // Node.js 使用 CommonJS
|
|
"lib": ["es2022"], // 包含的库文件
|
|
"outDir": "./dist", // 输出目录
|
|
"rootDir": "./src", // 源文件目录
|
|
"strict": true, // 启用所有严格类型检查选项
|
|
"esModuleInterop": true, // 允许默认导入非 ESModule 模块
|
|
"skipLibCheck": true, // 跳过所有声明文件的类型检查
|
|
"forceConsistentCasingInFileNames": true // 强制文件名大小写一致
|
|
},
|
|
"include": ["src/**/*"], // 包含的源文件
|
|
"exclude": ["node_modules", "dist"] // 排除的文件
|
|
}
|
|
```
|
|
|
|
```sh
|
|
pnpm add -D @types/node ts-node-dev tsconfig-paths
|
|
# tsconfig-paths 设置自定义路径
|
|
```
|
|
|
|
添加启动脚本 `package.json`
|
|
|
|
```
|
|
"scripts": {
|
|
"test": "echo \"Error: no test specified\" && exit 1",
|
|
"start": "node dist/index.js",
|
|
"dev": "NODE_ENV=dev nodemon --watch src -e ts --exec ts-node --esm src/index.ts",
|
|
"build": "tsc && tsc-alias"
|
|
},
|
|
```
|
|
|
|
创建目录和入口文件:
|
|
|
|
```sh
|
|
mkdir src
|
|
touch src/index.ts
|
|
```
|
|
|
|
编辑入口文件
|
|
|
|
```ts
|
|
// 导入 Fastify 和类型定义
|
|
import fastify, { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
|
|
|
// 创建 Fastify 实例
|
|
const server: FastifyInstance = fastify({
|
|
logger: true
|
|
});
|
|
|
|
// 你好啊,世界
|
|
server.get('/', (request: FastifyRequest, reply: FastifyReply) => {
|
|
return 'hello world'
|
|
})
|
|
|
|
// 定义一个 GET 路由
|
|
server.get('/ping', async (request: FastifyRequest, reply: FastifyReply) => {
|
|
return 'pong\n';
|
|
});
|
|
|
|
// 带参数的路由 /greetings/xiaoming
|
|
server.get('/greetings/:name', async (request: FastifyRequest, reply: FastifyReply) => {
|
|
// 使用类型断言获取参数
|
|
const name = (request.params as any).name as string;
|
|
return `Hello, ${name}!\n`;
|
|
});
|
|
|
|
// 带查询字符串的路由 /echo?message=hello
|
|
server.get('/echo', async (request: FastifyRequest, reply: FastifyReply) => {
|
|
// 使用类型断言获取查询参数
|
|
const message = (request.query as any).message as string;
|
|
return `You said: ${message}\n`;
|
|
});
|
|
|
|
// 异步路由处理器
|
|
server.get('/async-operation', async (request: FastifyRequest, reply: FastifyReply) => {
|
|
const result = await someAsyncOperation();
|
|
return result;
|
|
});
|
|
|
|
// 监听端口
|
|
server.listen({ port: 3000 }, (err, address) => {
|
|
if (err) {
|
|
server.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
server.log.info(`Server listening at ${address}`);
|
|
});
|
|
|
|
// 模拟的异步操作函数
|
|
async function someAsyncOperation(): Promise<string> {
|
|
return new Promise(resolve => setTimeout(() => resolve('Done!'), 1000));
|
|
}
|
|
``` |