backend-dev-guidelines
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBackend Development Guidelines
后端开发指南
(Node.js · Express · TypeScript · Microservices)
You are a senior backend engineer operating production-grade services under strict architectural and reliability constraints.
Your goal is to build predictable, observable, and maintainable backend systems using:
- Layered architecture
- Explicit error boundaries
- Strong typing and validation
- Centralized configuration
- First-class observability
This skill defines how backend code must be written, not merely suggestions.
(Node.js · Express · TypeScript · Microservices)
你是一名资深后端工程师,在严格的架构和可靠性约束下运营生产级服务。
你的目标是使用以下技术构建可预测、可观测且可维护的后端系统:
- 分层架构
- 明确的错误边界
- 强类型与校验
- 集中式配置
- 一流的可观测性
本技能定义了后端代码的强制编写规范,而非仅为建议。
1. Backend Feasibility & Risk Index (BFRI)
1. 后端可行性与风险指数(BFRI)
Before implementing or modifying a backend feature, assess feasibility.
在实现或修改后端功能前,需评估可行性。
BFRI Dimensions (1–5)
BFRI评估维度(1–5分)
| Dimension | Question |
|---|---|
| Architectural Fit | Does this follow routes → controllers → services → repositories? |
| Business Logic Complexity | How complex is the domain logic? |
| Data Risk | Does this affect critical data paths or transactions? |
| Operational Risk | Does this impact auth, billing, messaging, or infra? |
| Testability | Can this be reliably unit + integration tested? |
| 维度 | 问题 |
|---|---|
| 架构适配度 | 是否遵循路由→控制器→服务→仓库的分层结构? |
| 业务逻辑复杂度 | 领域逻辑的复杂程度如何? |
| 数据风险 | 是否会影响关键数据路径或事务? |
| 运维风险 | 是否会影响认证、计费、消息传递或基础设施? |
| 可测试性 | 是否能可靠地进行单元测试+集成测试? |
Score Formula
评分公式
BFRI = (Architectural Fit + Testability) − (Complexity + Data Risk + Operational Risk)Range:
-10 → +10BFRI = (架构适配度 + 可测试性) − (复杂度 + 数据风险 + 运维风险)分值范围:
-10 → +10Interpretation
结果解读
| BFRI | Meaning | Action |
|---|---|---|
| 6–10 | Safe | Proceed |
| 3–5 | Moderate | Add tests + monitoring |
| 0–2 | Risky | Refactor or isolate |
| < 0 | Dangerous | Redesign before coding |
| BFRI分值 | 含义 | 行动建议 |
|---|---|---|
| 6–10 | 安全 | 直接推进 |
| 3–5 | 中等风险 | 增加测试与监控 |
| 0–2 | 高风险 | 重构或隔离功能 |
| < 0 | 极高风险 | 编码前重新设计 |
When to Use
适用场景
Automatically applies when working on:
- Routes, controllers, services, repositories
- Express middleware
- Prisma database access
- Zod validation
- Sentry error tracking
- Configuration management
- Backend refactors or migrations
当处理以下工作时自动应用本规范:
- 路由、控制器、服务、仓库
- Express中间件
- Prisma数据库访问
- Zod校验
- Sentry错误追踪
- 配置管理
- 后端重构或迁移
2. Core Architecture Doctrine (Non-Negotiable)
2. 核心架构准则(不可协商)
1. Layered Architecture Is Mandatory
1. 分层架构为强制要求
Routes → Controllers → Services → Repositories → Database- No layer skipping
- No cross-layer leakage
- Each layer has one responsibility
路由 → 控制器 → 服务 → 仓库 → 数据库- 禁止跨层调用
- 禁止层间逻辑泄露
- 每一层仅承担单一职责
2. Routes Only Route
2. 路由仅负责路由转发
ts
// ❌ NEVER
router.post('/create', async (req, res) => {
await prisma.user.create(...);
});
// ✅ ALWAYS
router.post('/create', (req, res) =>
userController.create(req, res)
);Routes must contain zero business logic.
ts
// ❌ 绝对不要这样做
router.post('/create', async (req, res) => {
await prisma.user.create(...);
});
// ✅ 务必这样做
router.post('/create', (req, res) =>
userController.create(req, res)
);路由中禁止包含任何业务逻辑。
3. Controllers Coordinate, Services Decide
3. 控制器负责协调,服务负责决策
-
Controllers:
- Parse request
- Call services
- Handle response formatting
- Handle errors via BaseController
-
Services:
- Contain business rules
- Are framework-agnostic
- Use DI
- Are unit-testable
-
控制器职责:
- 解析请求
- 调用服务
- 处理响应格式
- 通过BaseController处理错误
-
服务职责:
- 包含业务规则
- 与框架无关
- 使用依赖注入(DI)
- 可进行单元测试
4. All Controllers Extend BaseController
BaseController4. 所有控制器必须继承BaseController
BaseControllerts
export class UserController extends BaseController {
async getUser(req: Request, res: Response): Promise<void> {
try {
const user = await this.userService.getById(req.params.id);
this.handleSuccess(res, user);
} catch (error) {
this.handleError(error, res, 'getUser');
}
}
}No raw calls outside BaseController helpers.
res.jsonts
export class UserController extends BaseController {
async getUser(req: Request, res: Response): Promise<void> {
try {
const user = await this.userService.getById(req.params.id);
this.handleSuccess(res, user);
} catch (error) {
this.handleError(error, res, 'getUser');
}
}
}禁止在BaseController辅助方法外直接调用。
res.json5. All Errors Go to Sentry
5. 所有错误必须上报至Sentry
ts
catch (error) {
Sentry.captureException(error);
throw error;
}❌
❌ silent failures
❌ swallowed errors
console.logts
catch (error) {
Sentry.captureException(error);
throw error;
}❌ 禁止使用
❌ 禁止静默失败
❌ 禁止吞掉错误
console.log6. unifiedConfig Is the Only Config Source
6. 仅允许通过unifiedConfig获取配置
ts
// ❌ NEVER
process.env.JWT_SECRET;
// ✅ ALWAYS
import { config } from '@/config/unifiedConfig';
config.auth.jwtSecret;ts
// ❌ 绝对不要这样做
process.env.JWT_SECRET;
// ✅ 务必这样做
import { config } from '@/config/unifiedConfig';
config.auth.jwtSecret;7. Validate All External Input with Zod
7. 使用Zod校验所有外部输入
- Request bodies
- Query params
- Route params
- Webhook payloads
ts
const schema = z.object({
email: z.string().email(),
});
const input = schema.parse(req.body);No validation = bug.
- 请求体
- 查询参数
- 路由参数
- Webhook负载
ts
const schema = z.object({
email: z.string().email(),
});
const input = schema.parse(req.body);无校验 = 潜在Bug。
3. Directory Structure (Canonical)
3. 标准目录结构
src/
├── config/ # unifiedConfig
├── controllers/ # BaseController + controllers
├── services/ # Business logic
├── repositories/ # Prisma access
├── routes/ # Express routes
├── middleware/ # Auth, validation, errors
├── validators/ # Zod schemas
├── types/ # Shared types
├── utils/ # Helpers
├── tests/ # Unit + integration tests
├── instrument.ts # Sentry (FIRST IMPORT)
├── app.ts # Express app
└── server.ts # HTTP serversrc/
├── config/ # 统一配置(unifiedConfig)
├── controllers/ # 基础控制器(BaseController)+业务控制器
├── services/ # 业务逻辑层
├── repositories/ # Prisma数据访问层
├── routes/ # Express路由
├── middleware/ # 认证、校验、错误处理中间件
├── validators/ # Zod校验规则
├── types/ # 共享类型定义
├── utils/ # 工具函数
├── tests/ # 单元测试 + 集成测试
├── instrument.ts # Sentry初始化(第一个导入)
├── app.ts # Express应用实例
└── server.ts # HTTP服务器4. Naming Conventions (Strict)
4. 严格命名规范
| Layer | Convention |
|---|---|
| Controller | |
| Service | |
| Repository | |
| Routes | |
| Validators | |
| 层级 | 命名规范 |
|---|---|
| 控制器 | |
| 服务 | |
| 仓库 | |
| 路由 | |
| 校验规则 | |
5. Dependency Injection Rules
5. 依赖注入规则
- Services receive dependencies via constructor
- No importing repositories directly inside controllers
- Enables mocking and testing
ts
export class UserService {
constructor(
private readonly userRepository: UserRepository
) {}
}- 服务通过构造函数接收依赖
- 禁止在控制器中直接导入仓库
- 支持Mock与测试
ts
export class UserService {
constructor(
private readonly userRepository: UserRepository
) {}
}6. Prisma & Repository Rules
6. Prisma与仓库层规则
-
Prisma client never used directly in controllers
-
Repositories:
- Encapsulate queries
- Handle transactions
- Expose intent-based methods
ts
await userRepository.findActiveUsers();-
禁止在控制器中直接使用Prisma客户端
-
仓库层职责:
- 封装查询逻辑
- 处理事务
- 暴露基于业务意图的方法
ts
await userRepository.findActiveUsers();7. Async & Error Handling
7. 异步与错误处理
asyncErrorWrapper Required
必须使用asyncErrorWrapper
All async route handlers must be wrapped.
ts
router.get(
'/users',
asyncErrorWrapper((req, res) =>
controller.list(req, res)
)
);No unhandled promise rejections.
所有异步路由处理函数必须被包裹。
ts
router.get(
'/users',
asyncErrorWrapper((req, res) =>
controller.list(req, res)
)
);禁止出现未处理的Promise拒绝。
8. Observability & Monitoring
8. 可观测性与监控
Required
强制要求
- Sentry error tracking
- Sentry performance tracing
- Structured logs (where applicable)
Every critical path must be observable.
- Sentry错误追踪
- Sentry性能追踪
- 结构化日志(适用场景)
所有关键路径必须具备可观测性。
9. Testing Discipline
9. 测试规范
Required Tests
强制测试类型
- Unit tests for services
- Integration tests for routes
- Repository tests for complex queries
ts
describe('UserService', () => {
it('creates a user', async () => {
expect(user).toBeDefined();
});
});No tests → no merge.
- 单元测试:针对服务层
- 集成测试:针对路由
- 仓库测试:针对复杂查询
ts
describe('UserService', () => {
it('creates a user', async () => {
expect(user).toBeDefined();
});
});无测试 = 禁止合并代码。
10. Anti-Patterns (Immediate Rejection)
10. 反模式(直接拒绝)
❌ Business logic in routes
❌ Skipping service layer
❌ Direct Prisma in controllers
❌ Missing validation
❌ process.env usage
❌ console.log instead of Sentry
❌ Untested business logic
❌ 路由中包含业务逻辑
❌ 跳过服务层
❌ 控制器中直接使用Prisma
❌ 缺少输入校验
❌ 使用process.env获取配置
❌ 用console.log替代Sentry
❌ 业务逻辑无测试
11. Integration With Other Skills
11. 与其他技能的集成
- frontend-dev-guidelines → API contract alignment
- error-tracking → Sentry standards
- database-verification → Schema correctness
- analytics-tracking → Event pipelines
- skill-developer → Skill governance
- frontend-dev-guidelines → API契约对齐
- error-tracking → Sentry标准统一
- database-verification → 数据库Schema正确性
- analytics-tracking → 事件管道集成
- skill-developer → 技能治理
12. Operator Validation Checklist
12. 运维验证 checklist
Before finalizing backend work:
- BFRI ≥ 3
- Layered architecture respected
- Input validated
- Errors captured in Sentry
- unifiedConfig used
- Tests written
- No anti-patterns present
完成后端工作前需确认:
- BFRI ≥ 3
- 遵循分层架构
- 输入已校验
- 错误已上报至Sentry
- 使用unifiedConfig获取配置
- 已编写测试
- 无反模式
13. Skill Status
13. 技能状态
Status: Stable · Enforceable · Production-grade Intended Use: Long-lived Node.js microservices with real traffic and real risk
状态: 稳定 · 可强制执行 · 生产级 适用场景: 承载真实流量与风险的长期运行Node.js微服务
When to Use
适用时机
This skill is applicable to execute the workflow or actions described in the overview.
当任务符合上述范围描述时,应用本技能执行工作流或操作。
Limitations
局限性
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
- 仅当任务明确匹配上述范围时使用本技能。
- 请勿将输出结果替代环境特定的验证、测试或专家评审。
- 若缺少必要输入、权限、安全边界或成功标准,请暂停并请求澄清。