service-best-practice

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Service 最佳实践

Service Best Practices

概述

Overview

在 code-arena 项目中,Service 层负责业务逻辑处理、数据转换和外部 API 集成。本技能提供编写 Service 的规范和最佳实践指导,确保代码的可维护性、可测试性和一致性。
In the code-arena project, the Service layer is responsible for business logic processing, data transformation, and external API integration. This skill provides specifications and best practice guidelines for writing Services to ensure code maintainability, testability, and consistency.

项目数据流

Project Data Flow

前端 React 组件 → tRPC 客户端 → tRPC 路由器 → Service → DAO → Drizzle DB → PostgreSQL
Frontend React components → tRPC Client → tRPC Router → Service → DAO → Drizzle DB → PostgreSQL

核心规范

Core Specifications

1. 文件结构

1. File Structure

  • 位置:
    apps/web/src/services/
  • 命名:
    {feature}Service.ts
  • 导出:
    export const {Feature}Service = { ... }
  • Location:
    apps/web/src/services/
  • Naming:
    {feature}Service.ts
  • Export:
    export const {Feature}Service = { ... }

2. 依赖注入(强制)

2. Dependency Injection (Mandatory)

Service 不得直接导入
db
,必须通过 DAO 依赖注入。
Services must not directly import
db
; they must use dependency injection via DAO.

3. 方法签名

3. Method Signatures

  • 驼峰命名
  • 返回 Promise 类型
  • 使用 Zod 验证输入
  • CamelCase naming
  • Return Promise type
  • Use Zod for input validation

4. 错误处理

4. Error Handling

使用自定义错误类,记录日志,抛出适当错误。
Use custom error classes, log records, and throw appropriate errors.

5. 事务管理

5. Transaction Management

Service 可发起
db.transaction()
,DAO 接收可选
tx
参数。
Services can initiate
db.transaction()
, and DAOs receive an optional
tx
parameter.

使用指南

Usage Guide

当创建或重构 Service 文件时:
  1. 遵循依赖注入模式
  2. 使用 Zod 验证输入
  3. 通过 DAO 处理数据库操作
  4. 实现适当错误处理和日志
  5. 编写测试用例
When creating or refactoring Service files:
  1. Follow the dependency injection pattern
  2. Use Zod for input validation
  3. Handle database operations via DAO
  4. Implement proper error handling and logging
  5. Write test cases

详细参考

Detailed Reference

完整的最佳实践指南请参阅 service-best-practice-guide.md,包含代码示例、模板和高级用法。
For the complete best practice guide, refer to service-best-practice-guide.md, which includes code examples, templates, and advanced usage.

资源

Resources

  • service-best-practice-guide.md:完整的 Service 编写指南
  • service-best-practice-guide.md: Complete Service writing guide