backend-dev-guidelines

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Backend Development Guidelines

后端开发指南

Purpose

目的

Establish consistency and best practices across backend microservices (blog-api, auth-service, notifications-service) using modern Node.js/Express/TypeScript patterns.
在使用现代Node.js/Express/TypeScript模式的后端微服务(blog-api、auth-service、notifications-service)中建立一致性与最佳实践。

When to Use This Skill

何时使用本技能

Automatically activates when working on:
  • Creating or modifying routes, endpoints, APIs
  • Building controllers, services, repositories
  • Implementing middleware (auth, validation, error handling)
  • Database operations with Prisma
  • Error tracking with Sentry
  • Input validation with Zod
  • Configuration management
  • Backend testing and refactoring

在以下场景下自动激活:
  • 创建或修改路由、端点、API
  • 构建控制器、服务、仓库
  • 实现中间件(认证、验证、错误处理)
  • 使用Prisma进行数据库操作
  • 使用Sentry进行错误追踪
  • 使用Zod进行输入验证
  • 配置管理
  • 后端测试与重构

Quick Start

快速开始

New Backend Feature Checklist

新后端功能检查清单

  • Route: Clean definition, delegate to controller
  • Controller: Extend BaseController
  • Service: Business logic with DI
  • Repository: Database access (if complex)
  • Validation: Zod schema
  • Sentry: Error tracking
  • Tests: Unit + integration tests
  • Config: Use unifiedConfig
  • 路由:清晰定义,委托给控制器处理
  • 控制器:继承BaseController
  • 服务:包含业务逻辑并使用依赖注入(DI)
  • 仓库:数据库访问(若逻辑复杂)
  • 验证:使用Zod schema
  • Sentry:错误追踪
  • 测试:单元测试 + 集成测试
  • 配置:使用unifiedConfig

New Microservice Checklist

新微服务检查清单

  • Directory structure (see architecture-overview.md)
  • instrument.ts for Sentry
  • unifiedConfig setup
  • BaseController class
  • Middleware stack
  • Error boundary
  • Testing framework

  • 目录结构(参考architecture-overview.md
  • 用于Sentry的instrument.ts
  • unifiedConfig配置
  • BaseController类
  • 中间件栈
  • 错误边界
  • 测试框架

Architecture Overview

架构概述

Layered Architecture

分层架构

HTTP Request
Routes (routing only)
Controllers (request handling)
Services (business logic)
Repositories (data access)
Database (Prisma)
Key Principle: Each layer has ONE responsibility.
See architecture-overview.md for complete details.

HTTP请求
路由(仅负责路由)
控制器(请求处理)
服务(业务逻辑)
仓库(数据访问)
数据库(Prisma)
核心原则:每个层仅承担单一职责。
完整细节请参考architecture-overview.md

Directory Structure

目录结构

service/src/
├── config/              # UnifiedConfig
├── controllers/         # Request handlers
├── services/            # Business logic
├── repositories/        # Data access
├── routes/              # Route definitions
├── middleware/          # Express middleware
├── types/               # TypeScript types
├── validators/          # Zod schemas
├── utils/               # Utilities
├── tests/               # Tests
├── instrument.ts        # Sentry (FIRST IMPORT)
├── app.ts               # Express setup
└── server.ts            # HTTP server
Naming Conventions:
  • Controllers:
    PascalCase
    -
    UserController.ts
  • Services:
    camelCase
    -
    userService.ts
  • Routes:
    camelCase + Routes
    -
    userRoutes.ts
  • Repositories:
    PascalCase + Repository
    -
    UserRepository.ts

service/src/
├── config/              # UnifiedConfig
├── controllers/         # 请求处理器
├── services/            # 业务逻辑
├── repositories/        # 数据访问
├── routes/              # 路由定义
├── middleware/          # Express中间件
├── types/               # TypeScript类型定义
├── validators/          # Zod schemas
├── 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

Core Principles (7 Key Rules)

核心原则(7条关键规则)

1. Routes Only Route, Controllers Control

1. 路由仅负责路由,控制器负责控制逻辑

typescript
// ❌ NEVER: Business logic in routes
router.post('/submit', async (req, res) => {
    // 200 lines of logic
});

// ✅ ALWAYS: Delegate to controller
router.post('/submit', (req, res) => controller.submit(req, res));
typescript
// ❌ 错误示例:在路由中编写业务逻辑
router.post('/submit', async (req, res) => {
    // 200行逻辑代码
});

// ✅ 正确示例:委托给控制器处理
router.post('/submit', (req, res) => controller.submit(req, res));

2. All Controllers Extend BaseController

2. 所有控制器继承BaseController

typescript
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');
        }
    }
}
typescript
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. All Errors to Sentry

3. 所有错误上报至Sentry

typescript
try {
    await operation();
} catch (error) {
    Sentry.captureException(error);
    throw error;
}
typescript
try {
    await operation();
} catch (error) {
    Sentry.captureException(error);
    throw error;
}

4. Use unifiedConfig, NEVER process.env

4. 使用unifiedConfig,禁止直接使用process.env

typescript
// ❌ NEVER
const timeout = process.env.TIMEOUT_MS;

// ✅ ALWAYS
import { config } from './config/unifiedConfig';
const timeout = config.timeouts.default;
typescript
// ❌ 错误示例
const timeout = process.env.TIMEOUT_MS;

// ✅ 正确示例
import { config } from './config/unifiedConfig';
const timeout = config.timeouts.default;

5. Validate All Input with Zod

5. 使用Zod验证所有输入

typescript
const schema = z.object({ email: z.string().email() });
const validated = schema.parse(req.body);
typescript
const schema = z.object({ email: z.string().email() });
const validated = schema.parse(req.body);

6. Use Repository Pattern for Data Access

6. 使用仓库模式进行数据访问

typescript
// Service → Repository → Database
const users = await userRepository.findActive();
typescript
// 服务 → 仓库 → 数据库
const users = await userRepository.findActive();

7. Comprehensive Testing Required

7. 必须进行全面测试

typescript
describe('UserService', () => {
    it('should create user', async () => {
        expect(user).toBeDefined();
    });
});

typescript
describe('UserService', () => {
    it('should create user', async () => {
        expect(user).toBeDefined();
    });
});

Common Imports

常用导入

typescript
// Express
import express, { Request, Response, NextFunction, Router } from 'express';

// Validation
import { z } from 'zod';

// Database
import { PrismaClient } from '@prisma/client';
import type { Prisma } from '@prisma/client';

// Sentry
import * as Sentry from '@sentry/node';

// Config
import { config } from './config/unifiedConfig';

// Middleware
import { SSOMiddlewareClient } from './middleware/SSOMiddleware';
import { asyncErrorWrapper } from './middleware/errorBoundary';

typescript
// 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';

Quick Reference

快速参考

HTTP Status Codes

HTTP状态码

CodeUse Case
200Success
201Created
400Bad Request
401Unauthorized
403Forbidden
404Not Found
500Server Error
状态码使用场景
200请求成功
201资源创建成功
400请求参数错误
401未授权
403禁止访问
404资源未找到
500服务器内部错误

Service Templates

服务模板

Blog API (✅ Mature) - Use as template for REST APIs Auth Service (✅ Mature) - Use as template for authentication patterns

Blog API(✅ 成熟)- 作为REST API的模板使用 Auth Service(✅ 成熟)- 作为认证模式的模板使用

Anti-Patterns to Avoid

需避免的反模式

❌ Business logic in routes ❌ Direct process.env usage ❌ Missing error handling ❌ No input validation ❌ Direct Prisma everywhere ❌ console.log instead of Sentry

❌ 在路由中编写业务逻辑 ❌ 直接使用process.env ❌ 缺失错误处理 ❌ 未进行输入验证 ❌ 随处直接使用Prisma ❌ 使用console.log而非Sentry

Navigation Guide

导航指南

Need to...Read this
Understand architecturearchitecture-overview.md
Create routes/controllersrouting-and-controllers.md
Organize business logicservices-and-repositories.md
Validate inputvalidation-patterns.md
Add error trackingsentry-and-monitoring.md
Create middlewaremiddleware-guide.md
Database accessdatabase-patterns.md
Manage configconfiguration.md
Handle async/errorsasync-and-errors.md
Write teststesting-guide.md
See examplescomplete-examples.md

需完成...参考文档
理解架构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

Resource Files

资源文件

architecture-overview.md

architecture-overview.md

Layered architecture, request lifecycle, separation of concerns
分层架构、请求生命周期、关注点分离

routing-and-controllers.md

routing-and-controllers.md

Route definitions, BaseController, error handling, examples
路由定义、BaseController、错误处理、示例

services-and-repositories.md

services-and-repositories.md

Service patterns, DI, repository pattern, caching
服务模式、依赖注入(DI)、仓库模式、缓存

validation-patterns.md

validation-patterns.md

Zod schemas, validation, DTO pattern
Zod schemas、验证、DTO模式

sentry-and-monitoring.md

sentry-and-monitoring.md

Sentry init, error capture, performance monitoring
Sentry初始化、错误捕获、性能监控

middleware-guide.md

middleware-guide.md

Auth, audit, error boundaries, AsyncLocalStorage
认证、审计、错误边界、AsyncLocalStorage

database-patterns.md

database-patterns.md

PrismaService, repositories, transactions, optimization
PrismaService、仓库、事务、优化

configuration.md

configuration.md

UnifiedConfig, environment configs, secrets
UnifiedConfig、环境配置、密钥管理

async-and-errors.md

async-and-errors.md

Async patterns, custom errors, asyncErrorWrapper
异步模式、自定义错误、asyncErrorWrapper

testing-guide.md

testing-guide.md

Unit/integration tests, mocking, coverage
单元/集成测试、Mock、覆盖率

complete-examples.md

complete-examples.md

Full examples, refactoring guide

完整示例、重构指南

Related Skills

相关技能

  • database-verification - Verify column names and schema consistency
  • error-tracking - Sentry integration patterns
  • skill-developer - Meta-skill for creating and managing skills

Skill Status: COMPLETE ✅ Line Count: < 500 ✅ Progressive Disclosure: 11 resource files ✅
  • database-verification - 验证列名与schema一致性
  • error-tracking - Sentry集成模式
  • skill-developer - 用于创建和管理技能的元技能

技能状态:已完成 ✅ 代码行数:< 500 ✅ 渐进式披露:11个资源文件 ✅