后端开发模式
用于可扩展服务器端应用程序的后端架构模式和最佳实践。
何时激活
- 设计 REST 或 GraphQL API 端点时
- 实现仓储层、服务层或控制器层时
- 优化数据库查询(N+1问题、索引、连接池)时
- 添加缓存(Redis、内存缓存、HTTP 缓存头)时
- 设置后台作业或异步处理时
- 为 API 构建错误处理和验证结构时
- 构建中间件(认证、日志记录、速率限制)时
API 设计模式
RESTful API 结构
// PASS: Resource-based URLs
GET /api/markets # List resources
GET /api/markets/:id # Get single resource
POST /api/markets # Create resource
PUT /api/markets/:id # Replace resource
PATCH /api/markets/:id # Update resource
DELETE /api/markets/:id # Delete resource
// PASS: Query parameters for filtering, sorting, pagination
GET /api/markets?status=active&sort=volume&limit=20&offset=0
仓储模式
// Abstract data access logic
interface MarketRepository {
findAll(filters?: MarketFilters): Promise<Market[]>
findById(id: string): Promise<Market | null>
create(data: CreateMarketDto): Promise<Market>
update(id: string, data: UpdateMarketDto): Promise<Market>
delete(id: string): Promise<void>
}
class SupabaseMarketRepository implements MarketRepository {
async findAll(filters?: MarketFilters): Promise<Market[]> {
l…