mcpField
B
backend-dev-guidelines

backend-dev-guidelines

github.com/bbeierle12开发959 次安装1 天前更新
代码仓库

关于 backend-dev-guidelines

为后端开发提供分层架构和实现模式指南,涵盖 Express 请求处理、数据访问、中间件与测试。适合构建和维护 TypeScript 后端 API 的开发者。

主要功能

  1. 01分层架构职责划分
  2. 02请求验证与中间件模式
  3. 03错误处理模式
  4. 04服务与路由测试示例
  5. 05数据库与认证参考文件

适用场景

  1. 01规划后端项目目录结构
  2. 02实现 Express API 请求流程
  3. 03为服务和路由编写测试

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/bbeierle12/skill-mcp-claude --skill backend-dev-guidelines

安装后在 Claude Code 中输入/backend-dev-guidelines确认已加载。

附带文件_meta.json

详细介绍

后端开发指南

分层架构

Request Flow:
Client → Routes → Controllers → Services → Repositories → Database

src/
├── routes/           # Route definitions
├── controllers/      # Request handling
├── services/         # Business logic
├── repositories/     # Data access
├── middleware/       # Express middleware
├── validators/       # Input validation
├── types/           # TypeScript types
├── utils/           # Utilities
└── config/          # Configuration

各层职责

路由层
  • 定义端点
  • 应用中间件
  • 将请求路由到控制器
// routes/users.routes.ts
import { Router } from 'express';
import { UserController } from '../controllers/user.controller';
import { validateRequest } from '../middleware/validate';
import { createUserSchema, updateUserSchema } from '../validators/user.validator';

const router = Router();
const controller = new UserController();

router.get('/', controller.getAll);
router.get('/:id', controller.getById);
router.post('/', validateRequest(createUserSchema), controller.create);
router.put('/:id', validateRequest(updateUserSchema), controller.update);
router.delete('/:id', controller.delete);

export default router;
控制器层
  • 处理 HTTP 请求和响应
  • 提取并验证输入
  • 调用服务
  • 返回响应
// controllers/user.controller.ts
import { Request, Response, NextFunction } from 'express';
import { UserService } from '../services/user.service';

export class UserController {
  private userService = new UserService();

  getAll = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const users = await this.userService.findAll();
      res.json({ data: users });
    } catch (error) {
      next(error);
    }
  };

  getById = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const { id } = req.params;
      const user = await this.userService.findById(id);
      
      if (!user) {
        return res.status(404).json({ error: 'User not found' });
      }
      
      res.json({ data: user });
    } catch (error) {
      next(error);
    }
  };

  create = async (req: Request, res: Response, next: NextFunction) => {
    try {
      const user = await this.userService.create(req.body);
      res.status(201).json({ data: user });
    } catch (error) {
      next(error);
    }
  };
}
服务层
  • 业务逻辑
  • 编排操作
  • 事务管理
// services/user.service.ts
import { UserRepository } from '../repositories/user.repository';
import { CreateUserDto, UpdateUserDto } from '../types/user.types';
import { AppError } from '../utils/errors';

export class UserService {
  private userRepository = new UserRepository();

  async findAll() {
    return this.userRepository.findAll();
  }

  async findById(id: string) {
    return this.userRepository.findById(id);
  }

  async create(data: CreateUserDto) {
    // Business logic
    const existingUser = await this.userRepository.findByEmail(data.email);
    if (existingUser) {
      throw new AppError('Email already exists', 409);
    }

    // Hash password, etc.
    const hashedPassword = await hashPassword(data.password);
    
    return this.userRepository.create({
      ...data,
      password: hashedPassword,
    });
  }

  async update(id: string, data: UpdateUserDto) {
    const user = await this.userRepository.findById(id);
    if (!user) {
      throw new AppError('User not found', 404);
    }

    return this.userRepository.update(id, data);
  }
}
仓库层
  • 数据库操作
  • 构建查询
  • 数据映射
// repositories/user.repository.ts
import { prisma } from '../config/database';
import { User, CreateUserInput, UpdateUserInput } from '../types/user.types';

export class UserRepository {
  async findAll(): Promise<User[]> {
    return prisma.user.findMany({
      select: {
        id: true,
        email: true,
        name: true,
        createdAt: true,
      },
    });
  }

  async findById(id: string): Promise<User | null> {
    return prisma.user.findUnique({
      where: { id },
    });
  }

  async findByEmail(email: string): Promise<User | null> {
    return prisma.user.findUnique({
      where: { email },
    });
  }

  async create(data: CreateUserInput): Promise<User> {
    return prisma.user.create({
      data,
    });
  }

  async update(id: string, data: UpdateUserInput): Promise<User> {
    return prisma.user.update({
      where: { id },
      data,
    });
  }

  async delete(id: string): Promise<void> {
    await prisma.user.delete({
      where: { id },
    });
  }
}

中间件模式

错误处理中间件
// middleware/error.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { AppError } from '../utils/errors';

export function errorHandler(
  error: Error,
  req: Request,
  res: Response,
  next: NextFunction
) {
  console.error('[Error]', {
    message: error.message,
    stack: error.stack,
    path: req.path,
    method: req.method,
  });

  if (error instanceof AppError) {
    return res.status(error.statusCode).json({
      error: error.message,
      code: error.code,
    });
  }

  // Don't expose internal errors
  res.status(500).json({
    error: 'Internal server error',
  });
}
验证中间件
// middleware/validate.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { ZodSchema } from 'zod';

export function validateRequest(schema: ZodSchema) {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse({
        body: req.body,
        query: req.query,
        params: req.params,
      });
      next();
    } catch (error) {
      res.status(400).json({
        error: 'Validation failed',
        details: error.errors,
      });
    }
  };
}
身份验证中间件
// middleware/auth.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { verifyToken } from '../utils/jwt';

export async function authenticate(
  req: Request,
  res: Response,
  next: NextFunction
) {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({ error: 'No token provided' });
    }

    const payload = await verifyToken(token);
    req.user = payload;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
}

输入验证

// validators/user.validator.ts
import { z } from 'zod';

export const createUserSchema = z.object({
  body: z.object({
    email: z.string().email(),
    password: z.string().min(8),
    name: z.string().min(2).max(100),
  }),
});

export const updateUserSchema = z.object({
  params: z.object({
    id: z.string().uuid(),
  }),
  body: z.object({
    name: z.string().min(2).max(100).optional(),
    email: z.string().email().optional(),
  }),
});

export type CreateUserDto = z.infer<typeof createUserSchema>['body'];
export type UpdateUserDto = z.infer<typeof updateUserSchema>['body'];

错误处理

// utils/errors.ts
export class AppError extends Error {
  constructor(
    message: string,
    public statusCode: number = 500,
    public code?: string
  ) {
    super(message);
    this.name = 'AppError';
  }
}

export class NotFoundError extends AppError {
  constructor(resource: string) {
    super(`${resource} not found`, 404, 'NOT_FOUND');
  }
}

export class ValidationError extends AppError {
  constructor(message: string) {
    super(message, 400, 'VALIDATION_ERROR');
  }
}

export class UnauthorizedError extends AppError {
  constructor(message = 'Unauthorized') {
    super(message, 401, 'UNAUTHORIZED');
  }
}

测试

单元测试(服务)
// services/user.service.test.ts
import { UserService } from './user.service';
import { UserRepository } from '../repositories/user.repository';

jest.mock('../repositories/user.repository');

describe('UserService', () => {
  let service: UserService;
  let mockRepository: jest.Mocked<UserRepository>;

  beforeEach(() => {
    mockRepository = new UserRepository() as jest.Mocked<UserRepository>;
    service = new UserService();
    (service as any).userRepository = mockRepository;
  });

  describe('create', () => {
    it('should throw if email exists', async () => {
      mockRepository.findByEmail.mockResolvedValue({ id: '1', email: '[email protected]' });

      await expect(service.create({
        email: '[email protected]',
        password: 'password',
        name: 'Test',
      })).rejects.toThrow('Email already exists');
    });

    it('should create user if email is unique', async () => {
      mockRepository.findByEmail.mockResolvedValue(null);
      mockRepository.create.mockResolvedValue({
        id: '1',
        email: '[email protected]',
        name: 'Test',
      });

      const result = await service.create({
        email: '[email protected]',
        password: 'password',
        name: 'Test',
      });

      expect(result.email).toBe('[email protected]');
    });
  });
});
集成测试(路由)
// routes/users.routes.test.ts
import request from 'supertest';
import { app } from '../app';

describe('Users API', () => {
  describe('GET /api/users', () => {
    it('should return all users', async () => {
      const response = await request(app)
        .get('/api/users')
        .expect(200);

      expect(response.body.data).toBeInstanceOf(Array);
    });
  });

  describe('POST /api/users', () => {
    it('should create a user', async () => {
      const response = await request(app)
        .post('/api/users')
        .send({
          email: '[email protected]',
          password: 'password123',
          name: 'Test User',
        })
        .expect(201);

      expect(response.body.data.email).toBe('[email protected]');
    });

    it('should validate input', async () => {
      await request(app)
        .post('/api/users')
        .send({
          email: 'invalid-email',
        })
        .expect(400);
    });
  });
});

资源文件

详细模式请参阅:

评论

支持 Markdown