name: backend-implementation-patterns description: 生产就绪的后端 API 实现模式,包括 REST、GraphQL、认证、错误处理和數據驗證 license: MIT metadata: adapted-by: ai-skills category: backend-development
后端实现模式
用于构建稳健、可扩展的后端 API 的生产就绪模式。
API 设计模式
RESTful 端点
// 基于资源的路由
app.get('/api/users', getUsers); // 列表
app.get('/api/users/:id', getUserById); // 获取
app.post('/api/users', createUser); // 创建
app.put('/api/users/:id', updateUser); // 更新
app.delete('/api/users/:id', deleteUser); // 删除
// 嵌套资源
app.get('/api/users/:id/posts', getUserPosts);
app.post('/api/users/:id/posts', createUserPost);
请求/响应模式
interface APIResponse<T> {
success: boolean;
data?: T;
error?: {
code: string;
message: string;
details?: any;
};
meta?: {
page?: number;
limit?: number;
total?: number;
};
}
async function handleRequest<T>(
handler: () => Promise<T>
): Promise<APIResponse<T>> {
try {
const data = await handler();
return { success: true, data };
} catch (error) {
return {
success: false,
error: {
code: error.code || 'INTERNAL_ERROR',
message: error.message,
}
};
}
}
验证层
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
age: z.number().int().min(18).optional(),
});
app.post('/api/users', async (req, res) => {
const validation = CreateUserSchema.safeParse(req.body);
if (!validation.success) {
return res.status(400).json({
success: false,
error: {
code: 'VALIDATION_ERROR',
message: '无效的请求数据',
details: validation.error.errors
}
});
}
const user = await userService.create(validation.data);
res.status(201).json({ success: true, data: user });
});
认证模式
JWT 认证
import jwt from 'jsonwebtoken';
// 生成令牌
function generateToken(userId: string) {
return jwt.sign(
{ userId },
process.env.JWT_SECRET!, // allow-secret
{ expiresIn: '7d' }
);
}
// 中间件
async function authenticateToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1]; // allow-secret
if (!token) {
return res.status(401).json({
success: false,
error: { code: 'UNAUTHORIZED', message: '缺少令牌' }
});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET!); // allow-secret
req.userId = decoded.userId;
next();
} catch (error) {
return res.status(401).json({
success: false,
error: { code: 'INVALID_TOKEN', message: '无效或过期的令牌' }
});
}
}
错误处理
自定义错误类
class AppError extends Error {
constructor(
public statusCode: number,
public code: string,
message: string,
public details?: any
) {
super(message);
this.name = 'AppError';
}
}
class NotFoundError extends AppError {
constructor(resource: string) {
super(404, 'NOT_FOUND', `${resource} 未找到`);
}
}
class ValidationError extends AppError {
constructor(details: any) {
super(400, 'VALIDATION_ERROR', '验证失败', details);
}
}
错误处理中间件
app.use((error, req, res, next) => {
console.error('错误:', error);
if (error instanceof AppError) {
return res.status(error.statusCode).json({
success: false,
error: {
code: error.code,
message: error.message,
details: error.details
}
});
}
res.status(500).json({
success: false,
error: {
code: 'INTERNAL_ERROR',
message: '发生意外错误'
}
});
});
数据访问层
仓库模式
interface Repository<T> {
find Find(filters: any): Promise<T[]>;
findById(id: string): Promise<T | null>;
create(data: Partial<T>): Promise<T>;
update(id: string, data: Partial<T>): Promise<T>;
delete(id: string): Promise<void>;
}
class UserRepository implements Repository<User> {
async findById(id: string): Promise<User | null> {
return db.user.findUnique({ where: { id } });
}
async create(data: Partial<User>): Promise<User> {
return db.user.create({ data });
}
// ... 其他方法
}
速率限制
import rateLimit from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 分钟
max: 100, // 每个窗口 100 个请求
message: { success: false, error: { code: 'RATE_LIMIT', message: '请求过多' }}
});
app.use('/api/', limiter);
集成点
补充:
- api-design-patterns:用于 API 结构
- postgres-advanced-patterns:用于数据层
- security-implementation-guide:用于安全
- tdd-workflow:用于测试
相关技能
互补技能(一起使用)
- api-design-patterns - 在实现之前设计你的 API 结构
- postgres-advanced-patterns - 数据层的高级数据库模式
- testing-patterns - 为你的 API 端点编写测试
- deployment-cicd - 部署你的后端服务
替代技能(类似目的)
- nextjs-fullstack-patterns - 如果使用 Next.js App Router 构建
先修技能(先学习)
- api-design-patterns - 理解 API 设计有助于结构实现