backend-dev-guidelines

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Backend 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)

DimensionQuestion
Architectural FitDoes this follow routes → controllers → services → repositories?
Business Logic ComplexityHow complex is the domain logic?
Data RiskDoes this affect critical data paths or transactions?
Operational RiskDoes this impact auth, billing, messaging, or infra?
TestabilityCan this be reliably unit + integration tested?
维度问题
架构契合度是否遵循路由→控制器→服务→数据仓库的分层结构?
业务逻辑复杂度领域逻辑的复杂程度如何?
数据风险是否会影响关键数据路径或事务?
运维风险是否会影响认证、计费、消息传递或基础设施?
可测试性是否能可靠地进行单元测试与集成测试?

Score Formula

评分公式

BFRI = (Architectural Fit + Testability) − (Complexity + Data Risk + Operational Risk)
Range:
-10 → +10
BFRI = (架构契合度 + 可测试性) − (复杂度 + 数据风险 + 运维风险)
范围:
-10 → +10

Interpretation

结果解读

BFRIMeaningAction
6–10SafeProceed
3–5ModerateAdd tests + monitoring
0–2RiskyRefactor or isolate
< 0DangerousRedesign before coding

BFRI含义操作建议
6–10安全继续推进
3–5中等风险添加测试与监控
0–2高风险重构或隔离功能
< 0危险编码前重新设计

2. When to Use This Skill

2. 本技能的适用场景

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错误追踪
  • 配置管理
  • 后端重构或迁移

3. Core Architecture Doctrine (Non-Negotiable)

3. 核心架构原则(不可妥协)

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

4. 所有控制器必须继承
BaseController

ts
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
res.json
calls outside BaseController helpers.

ts
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.json

5. All Errors Go to Sentry

5. 所有错误必须上报至Sentry

ts
catch (error) {
  Sentry.captureException(error);
  throw error;
}
console.log
❌ silent failures ❌ swallowed errors

ts
catch (error) {
  Sentry.captureException(error);
  throw error;
}
❌ 禁止使用
console.log
❌ 禁止静默失败 ❌ 禁止吞掉错误

6. 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);
无验证 = 漏洞。

4. Directory Structure (Canonical)

4. 标准目录结构

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 server

src/
├── config/              # unified配置
├── controllers/         # BaseController + 业务控制器
├── services/            # 业务逻辑
├── repositories/        # Prisma数据库访问
├── routes/              # Express路由
├── middleware/          # 认证、验证、错误处理中间件
├── validators/          # Zod验证规则
├── types/               # 共享类型定义
├── utils/               # 工具函数
├── tests/               # 单元测试 + 集成测试
├── instrument.ts        # Sentry初始化(第一个导入)
├── app.ts               # Express应用实例
└── server.ts            # HTTP服务器

5. Naming Conventions (Strict)

5. 严格命名规范

LayerConvention
Controller
PascalCaseController.ts
Service
camelCaseService.ts
Repository
PascalCaseRepository.ts
Routes
camelCaseRoutes.ts
Validators
camelCase.schema.ts

层级命名规范
控制器
PascalCaseController.ts
服务
camelCaseService.ts
数据仓库
PascalCaseRepository.ts
路由
camelCaseRoutes.ts
验证器
camelCase.schema.ts

6. Dependency Injection Rules

6. 依赖注入规则

  • Services receive dependencies via constructor
  • No importing repositories directly inside controllers
  • Enables mocking and testing
ts
export class UserService {
  constructor(
    private readonly userRepository: UserRepository
  ) {}
}

  • 服务通过构造函数接收依赖
  • 禁止在控制器中直接导入数据仓库
  • 便于模拟与测试
ts
export class UserService {
  constructor(
    private readonly userRepository: UserRepository
  ) {}
}

7. Prisma & Repository Rules

7. 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();

8. Async & Error Handling

8. 异步与错误处理

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拒绝。

9. Observability & Monitoring

9. 可观测性与监控

Required

强制要求

  • Sentry error tracking
  • Sentry performance tracing
  • Structured logs (where applicable)
Every critical path must be observable.

  • Sentry错误追踪
  • Sentry性能追踪
  • 结构化日志(如适用)
所有关键路径必须具备可观测性。

10. Testing Discipline

10. 测试规范

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();
  });
});
无测试 = 禁止合并代码。

11. Anti-Patterns (Immediate Rejection)

11. 反模式(直接拒绝)

❌ 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 ❌ 业务逻辑未测试

12. Integration With Other Skills

12. 与其他技能的集成

  • 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 → 技能治理

13. Operator Validation Checklist

13. 运维人员验证清单

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
  • 已编写测试
  • 无反模式

14. Skill Status

14. 技能状态

Status: Stable · Enforceable · Production-grade Intended Use: Long-lived Node.js microservices with real traffic and real risk

状态: 稳定 · 可强制执行 · 生产级 预期用途: 承载真实流量与风险的长期运行Node.js微服务