# 标准通用CRUD开发流程规范

## 适用场景

适用于简单数据模型，无复杂业务逻辑，仅需基础CRUD操作的场景。采用`GenericCrudService`和`createCrudRoutes`快速生成接口。

## 开发流程

### 1. **创建实体**
   - 位置: `src/server/modules/[模块名]/[实体名].entity.ts`
   - 参考已有实体文件如`user.entity.ts`
   - 注意: 必须包含Zod Schema定义

### 2. **注册实体到数据源**
   - 在`src/server/data-source.ts`中添加实体导入和注册:
     ```typescript
     // 实体类导入
     import { YourEntity } from "./modules/[模块名]/[实体名].entity"
     
     export const AppDataSource = new DataSource({
       // ...其他配置
       entities: [
         User, Role, YourEntity // 添加新实体到数组
       ],
       // ...其他配置
     });
     ```

### 3. **创建Service**
   - 位置: `src/server/modules/[模块名]/[实体名].service.ts`
   - 继承`GenericCrudService`
   - 通过构造函数注入DataSource
   ```typescript
   import { GenericCrudService } from '@/server/utils/generic-crud.service';
   import { DataSource } from 'typeorm';
   import { YourEntity } from './your-entity.entity';
   
   export class YourEntityService extends GenericCrudService<YourEntity> {
     constructor(dataSource: DataSource) {
       super(dataSource, YourEntity);
     }
   }
   ```

### 4. **创建API路由**
   - 使用`createCrudRoutes`快速生成CRUD路由:
     ```typescript
     import { createCrudRoutes } from '@/server/utils/generic-crud.routes';
     import { YourEntity } from '@/server/modules/your-module/your-entity.entity';
     import { YourEntitySchema, CreateYourEntityDto, UpdateYourEntityDto } from '@/server/modules/your-module/your-entity.entity';
     import { authMiddleware } from '@/server/middleware/auth.middleware';
     
     const yourEntityRoutes = createCrudRoutes({
       entity: YourEntity,
       createSchema: CreateYourEntityDto,
       updateSchema: UpdateYourEntityDto,
       getSchema: YourEntitySchema,
       listSchema: YourEntitySchema,
       searchFields: ['name', 'description'], // 可选，指定搜索字段
       middleware: [authMiddleware] // 可选，添加中间件
     });
     
     export default yourEntityRoutes;
     ```

### 5. **注册路由**
   - 在`src/server/api.ts`中添加路由注册:
     ```typescript
     import yourEntityRoutes from '@/server/api/your-entity/index';
     
     // 注册路由
     api.route('/api/v1/your-entities', yourEntityRoutes);
     ```

### 6. **创建客户端API**
   - 在`src/client/api.ts`中添加客户端定义:
     ```typescript
     import { hc } from 'hono/client';
     import { YourEntityRoutes } from '@/server/api';
     
     export const yourEntityClient = hc<YourEntityRoutes>('/api/v1', {
       fetch: axiosFetch,
     }).api.v1['your-entities'];
     ```

### 7. **前端调用**
   - 在页面组件(如`Users.tsx`)中:
     - 使用`InferResponseType`提取响应类型
     - 使用`InferRequestType`提取请求类型
     - 示例:
       ```typescript
       type EntityResponse = InferResponseType<typeof entityClient.$get, 200>;
       type CreateRequest = InferRequestType<typeof entityClient.$post>['json'];
       ```

### 8. **注册管理后台路由和菜单**
    - **注册路由**：在`src/client/admin/routes.tsx`中添加路由配置
      
    - **注册菜单**：在`src/client/admin/menu.tsx`中添加菜单配置

