[ PROMPT_NODE_23756 ]
完整代码示例
[ SKILL_DOCUMENTATION ]
# 完整示例 - 可运行的完整代码
展示完整实现模式的真实世界代码示例。
## 目录
- [控制器完整示例](#控制器完整示例)
- [带有依赖注入的服务完整示例](#带有依赖注入的服务完整示例)
- [路由文件完整示例](#路由文件完整示例)
- [仓库完整示例](#仓库完整示例)
- [重构示例:从差到好](#重构示例-从差到好)
- [端到端功能示例](#端到端功能示例)
---
## 控制器完整示例
### UserController (遵循所有最佳实践)
typescript
// controllers/UserController.ts
import { Request, Response } from 'express';
import { BaseController } from './BaseController';
import { UserService } from '../services/userService';
import { createUserSchema, updateUserSchema } from '../validators/userSchemas';
import { z } from 'zod';
export class UserController extends BaseController {
private userService: UserService;
constructor() {
super();
this.userService = new UserService();
}
async getUser(req: Request, res: Response): Promise {
try {
this.addBreadcrumb('Fetching user', 'user_controller', {
userId: req.params.id,
});
const user = await this.withTransaction(
'user.get',
'db.query',
() => this.userService.findById(req.params.id)
);
if (!user) {
return this.handleError(
new Error('User not found'),
res,
'getUser',
404
);
}
this.handleSuccess(res, user);
} catch (error) {
this.handleError(error, res, 'getUser');
}
}
async listUsers(req: Request, res: Response): Promise {
try {
const users = await this.userService.getAll();
this.handleSuccess(res, users);
} catch (error) {
this.handleError(error, res, 'listUsers');
}
}
async createUser(req: Request, res: Response): Promise {
try {
// 使用 Zod 验证输入
const validated = createUserSchema.parse(req.body);
// 跟踪性能
const user = await this.withTransaction(
'user.create',
'db.mutation',
() => this.userService.create(validated)
);