后端开发指南
目的
建立使用现代Node.js/Express/TypeScript模式的后端微服务(blog-api, auth-service, notifications-service)之间的一致性和最佳实践。
何时使用此技能
自动激活时进行以下工作:
- 创建或修改路由、端点、API
- 构建控制器、服务、仓库
- 实施中间件(认证、验证、错误处理)
- 使用Prisma进行数据库操作
- 使用Sentry进行错误跟踪
- 使用Zod进行输入验证
- 配置管理
- 后端测试和重构
快速开始
新后端功能检查清单
- [ ] 路由:清晰定义,委托给控制器
- [ ] 控制器:扩展BaseController
- [ ] 服务:带有DI的业务逻辑
- [ ] 仓库:数据库访问(如果复杂)
- [ ] 验证:Zod模式
- [ ] Sentry:错误跟踪
- [ ] 测试:单元+集成测试
- [ ] 配置:使用unifiedConfig
新微服务检查清单
- [ ] 目录结构(见architecture-overview.md)
- [ ] instrument.ts用于Sentry
- [ ] unifiedConfig设置
- [ ] BaseController类
- [ ] 中间件堆栈
- [ ] 错误边界
- [ ] 测试框架
架构概览
分层架构
HTTP请求
↓
路由(仅路由)
↓
控制器(请求处理)
↓
服务(业务逻辑)
↓
仓库(数据访问)
↓
数据库(Prisma)
**关键原则:**每一层只有一个责任。
见architecture-overview.md了解详细信息。
目录结构
service/src/
├── config/ # UnifiedConfig
├── controllers/ # 请求处理程序
├── services/ # 业务逻辑
├── repositories/ # 数据访问
├── routes/ # 路由定义
├── middleware/ # Express中间件
├── types/ # TypeScript类型
├── validators/ # Zod模式
├── utils/ # 实用程序
├── tests/ # 测试
├── instrument.ts # Sentry(首先导入)
├── app.ts # Express设置
└── server.ts # HTTP服务器
命名约定:
- 控制器:
PascalCase-UserController.ts - 服务:
camelCase-userService.ts - 路由:
camelCase + Routes-userRoutes.ts - 仓库:
PascalCase + Repository-UserRepository.ts
核心原则(7个关键规则)
1. 路由仅路由,控制器控制
// ❌ 永不:路由中的业务逻辑
router.post('/submit', async (req, res) => {
// 200行逻辑
});
// ✅ 总是:委托给控制器
router.post('/submit', (req, res) => controller.submit(req, res));
2. 所有控制器扩展BaseController
export class UserController extends BaseController {
async getUser(req: Request, res: Response): Promise<void> {
try {
const user = await this.userService.findById(req.params.id);
this.handleSuccess(res, user);
} catch (error) {
this.handleError(error, res, 'getUser');
}
}
}
3. 所有错误到Sentry
try {
await operation();
} catch (error) {
Sentry.captureException(error);
throw error;
}
4. 使用unifiedConfig,永不process.env
// ❌ 永不
const timeout = process.env.TIMEOUT_MS;
// ✅ 总是
import { config } from './config/unifiedConfig';
const timeout = config.timeouts.default;
5. 使用Zod验证所有输入
const schema = z.object({ email: z.string().email() });
const validated = schema.parse(req.body);
6. 使用仓库模式进行数据访问
// 服务 → 仓库 → 数据库
const users = await userRepository.findActive();
7. 需要全面测试
describe('UserService', () => {
it('should create user', async () => {
expect(user).toBeDefined();
});
});
常见导入
// Express
import express, { Request, Response, NextFunction, Router } from 'express';
// 验证
import { z } from 'zod';
// 数据库
import { PrismaClient } from '@prisma/client';
import type { Prisma } from '@prisma/client';
// Sentry
import * as Sentry from '@sentry/node';
// 配置
import { config } from './config/unifiedConfig';
// 中间件
import { SSOMiddlewareClient } from './middleware/SSOMiddleware';
import { asyncErrorWrapper } from './middleware/errorBoundary';
快速参考
HTTP状态代码
| 代码 | 用例 |
|---|---|
| 200 | 成功 |
| 201 | 已创建 |
| 400 | 错误请求 |
| 401 | 未授权 |
| 403 | 禁止 |
| 404 | 未找到 |
| 500 | 服务器错误 |
服务模板
博客API (✅ 成熟) - 用作REST API的模板 认证服务 (✅ 成熟) - 用作认证模式的模板
避免的反模式
❌ 路由中的业务逻辑 ❌ 直接process.env使用 ❌ 缺少错误处理 ❌ 没有输入验证 ❌ 到处直接使用Prisma ❌ 使用console.log而不是Sentry
导航指南
| 需要… | 阅读此 |
|---|---|
| 理解架构 | architecture-overview.md |
| 创建路由/控制器 | routing-and-controllers.md |
| 组织业务逻辑 | services-and-repositories.md |
| 验证输入 | validation-patterns.md |
| 添加错误跟踪 | sentry-and-monitoring.md |
| 创建中间件 | middleware-guide.md |
| 数据库访问 | database-patterns.md |
| 管理配置 | configuration.md |
| 处理异步/错误 | async-and-errors.md |
| 编写测试 | testing-guide.md |
| 查看示例 | complete-examples.md |
资源文件
architecture-overview.md
分层架构,请求生命周期,关注点分离
routing-and-controllers.md
路由定义,BaseController,错误处理,示例
services-and-repositories.md
服务模式,DI,仓库模式,缓存
validation-patterns.md
Zod模式,验证,DTO模式
sentry-and-monitoring.md
Sentry初始化,错误捕获,性能监控
middleware-guide.md
认证,审计,错误边界,AsyncLocalStorage
database-patterns.md
PrismaService,仓库,事务,优化
configuration.md
UnifiedConfig,环境配置,机密
async-and-errors.md
异步模式,自定义错误,asyncErrorWrapper
testing-guide.md
单元/集成测试,模拟,覆盖率
complete-examples.md
完整示例,重构指南
相关技能
- database-verification - 验证列名和架构一致性
- error-tracking - Sentry集成模式
- skill-developer - 创建和管理技能的元技能
技能状态: 完成 ✅ 行数: < 500 ✅ 逐步披露: 11个资源文件 ✅