Преглед на файлове

♻️ refactor(api): 重构地点管理API实现

- 移除全局serviceMiddleware中间件,优化请求处理流程
- 删除locations模块中的自定义搜索和区域查询路由,统一使用通用CRUD路由
- 移除LocationService服务类,简化业务逻辑实现

🔧 chore: 删除冗余文件和代码

- 删除server/middleware/service.middleware.ts文件
- 删除modules/locations/location.service.ts文件
- 清理locations API中的未使用导入和schema定义
yourname преди 4 месеца
родител
ревизия
3ca0acd80b
променени са 4 файла, в които са добавени 0 реда и са изтрити 301 реда
  1. 0 4
      src/server/api.ts
  2. 0 61
      src/server/api/admin/locations/index.ts
  3. 0 21
      src/server/middleware/service.middleware.ts
  4. 0 215
      src/server/modules/locations/location.service.ts

+ 0 - 4
src/server/api.ts

@@ -14,7 +14,6 @@ import { AuthContext } from './types/context'
 import { AppDataSource } from './data-source'
 import { Hono } from 'hono'
 import { databaseBackup } from './utils/backup'
-import { serviceMiddleware } from './middleware/service.middleware'
 
 if(!AppDataSource.isInitialized) {
   await AppDataSource.initialize();
@@ -36,9 +35,6 @@ api.use('/api/v1/*', async (_, next) => {
   await next()
 })
 
-// 服务注册中间件
-api.use('/api/v1/*', serviceMiddleware)
-
 // // 数据库初始化中间件
 // api.use('/api/v1/*', async (c, next) => {
 //   await next();

+ 0 - 61
src/server/api/admin/locations/index.ts

@@ -5,14 +5,8 @@ import {
   createLocationSchema,
   updateLocationSchema,
   getLocationSchema,
-  listLocationsSchema,
-  deleteLocationSchema,
-  toggleLocationStatusSchema,
-  searchLocationsSchema,
   locationListResponseSchema
 } from '@/server/modules/locations/location.schema';
-import { LocationService } from '@/server/modules/locations/location.service';
-import { AppDataSource } from '@/server/data-source';
 
 // 使用通用CRUD路由创建地点管理API
 export default createCrudRoutes({
@@ -24,59 +18,4 @@ export default createCrudRoutes({
   searchFields: ['name', 'address'],
   relations: ['province', 'city', 'district'],
   middleware: [authMiddleware]
-})
-// 搜索地点
-.get('/search', authMiddleware, async (c) => {
-  try {
-    const params = c.req.query();
-    const validation = searchLocationsSchema.safeParse(params);
-    if (!validation.success) {
-      return c.json({
-        success: false,
-        message: '参数验证失败',
-        errors: validation.error.errors
-      }, 400);
-    }
-
-    const locationService = new LocationService(AppDataSource);
-    const locations = await locationService.searchLocations(validation.data);
-    return c.json({
-      success: true,
-      data: locations,
-      message: '搜索地点成功'
-    });
-  } catch (error) {
-    console.error('搜索地点失败:', error);
-    return c.json({
-      success: false,
-      message: '搜索地点失败',
-      error: error instanceof Error ? error.message : '未知错误'
-    }, 500);
-  }
-})
-// 根据省市区ID获取地点
-.get('/by-areas', authMiddleware, async (c) => {
-  try {
-    const { provinceId, cityId, districtId } = c.req.query();
-
-    const locationService = c.get('locationService');
-    const locations = await locationService.findByAreaIds({
-      provinceId: provinceId ? Number(provinceId) : undefined,
-      cityId: cityId ? Number(cityId) : undefined,
-      districtId: districtId ? Number(districtId) : undefined
-    });
-
-    return c.json({
-      success: true,
-      data: locations,
-      message: '获取地点列表成功'
-    });
-  } catch (error) {
-    console.error('获取地点列表失败:', error);
-    return c.json({
-      success: false,
-      message: '获取地点列表失败',
-      error: error instanceof Error ? error.message : '未知错误'
-    }, 500);
-  }
 });

+ 0 - 21
src/server/middleware/service.middleware.ts

@@ -1,21 +0,0 @@
-import { Context, Next } from 'hono';
-import { AppDataSource } from '../data-source';
-import { AreaService } from '../modules/areas/area.service';
-import { LocationService } from '../modules/locations/location.service';
-
-export async function serviceMiddleware(c: Context, next: Next) {
-  try {
-    // 注册区域服务
-    const areaService = new AreaService(AppDataSource);
-    c.set('areaService', areaService);
-
-    // 注册地点服务
-    const locationService = new LocationService(AppDataSource);
-    c.set('locationService', locationService);
-
-    await next();
-  } catch (error) {
-    console.error('Service middleware error:', error);
-    return c.json({ message: 'Service initialization failed' }, 500);
-  }
-}

+ 0 - 215
src/server/modules/locations/location.service.ts

@@ -1,215 +0,0 @@
-import { DataSource, Repository } from 'typeorm';
-import { LocationEntity } from './location.entity';
-import { CreateLocationInput, UpdateLocationInput } from './location.schema';
-import { DisabledStatus } from '@/share/types';
-export class LocationService {
-  private locationRepository: Repository<LocationEntity>;
-
-  constructor(private dataSource: DataSource) {
-    this.locationRepository = this.dataSource.getRepository(LocationEntity);
-  }
-
-  /**
-   * 创建地点
-   */
-  async create(input: CreateLocationInput): Promise<LocationEntity> {
-    const location = this.locationRepository.create(input);
-    return await this.locationRepository.save(location);
-  }
-
-  /**
-   * 更新地点
-   */
-  async update(id: number, input: UpdateLocationInput): Promise<LocationEntity | null> {
-    const location = await this.locationRepository.findOne({
-      where: { id },
-      relations: ['province', 'city', 'district']
-    });
-    if (!location) {
-      return null;
-    }
-
-    Object.assign(location, input);
-    return await this.locationRepository.save(location);
-  }
-
-  /**
-   * 获取地点详情
-   */
-  async findById(id: number): Promise<LocationEntity | null> {
-    return await this.locationRepository.findOne({
-      where: { id },
-      relations: ['province', 'city', 'district']
-    });
-  }
-
-  /**
-   * 获取地点列表
-   */
-  async findAll(params: {
-    keyword?: string;
-    provinceId?: number;
-    cityId?: number;
-    districtId?: number;
-    isDisabled?: DisabledStatus;
-    page?: number;
-    pageSize?: number;
-    sortBy?: string;
-    sortOrder?: 'ASC' | 'DESC';
-  }): Promise<{ data: LocationEntity[]; total: number }> {
-    const {
-      keyword,
-      provinceId,
-      cityId,
-      districtId,
-      isDisabled,
-      page = 1,
-      pageSize = 20,
-      sortBy = 'createdAt',
-      sortOrder = 'DESC'
-    } = params;
-
-    const queryBuilder = this.locationRepository
-      .createQueryBuilder('location')
-      .leftJoinAndSelect('location.province', 'province')
-      .leftJoinAndSelect('location.city', 'city')
-      .leftJoinAndSelect('location.district', 'district')
-      .where('location.isDeleted = :isDeleted', { isDeleted: 0 });
-
-    // 关键词搜索
-    if (keyword) {
-      queryBuilder.andWhere('(location.name LIKE :keyword OR location.address LIKE :keyword)', {
-        keyword: `%${keyword}%`
-      });
-    }
-
-    // 省份筛选
-    if (provinceId) {
-      queryBuilder.andWhere('location.provinceId = :provinceId', { provinceId });
-    }
-
-    // 城市筛选
-    if (cityId) {
-      queryBuilder.andWhere('location.cityId = :cityId', { cityId });
-    }
-
-    // 区县筛选
-    if (districtId) {
-      queryBuilder.andWhere('location.districtId = :districtId', { districtId });
-    }
-
-    // 状态筛选
-    if (isDisabled !== undefined) {
-      queryBuilder.andWhere('location.isDisabled = :isDisabled', { isDisabled });
-    }
-
-    // 排序
-    const orderBy = `location.${sortBy}`;
-    queryBuilder.orderBy(orderBy, sortOrder);
-
-    // 分页
-    const [data, total] = await queryBuilder
-      .skip((page - 1) * pageSize)
-      .take(pageSize)
-      .getManyAndCount();
-
-    return { data, total };
-  }
-
-  /**
-   * 删除地点(软删除)
-   */
-  async delete(id: number): Promise<boolean> {
-    const result = await this.locationRepository.update(id, { isDeleted: 1 });
-    return result.affected !== 0;
-  }
-
-  /**
-   * 启用/禁用地点
-   */
-  async toggleStatus(id: number, isDisabled: DisabledStatus): Promise<boolean> {
-    const result = await this.locationRepository.update(id, { isDisabled });
-    return result.affected !== 0;
-  }
-
-  /**
-   * 搜索地点
-   */
-  async searchLocations(params: {
-    keyword?: string;
-    provinceId?: number;
-    cityId?: number;
-    districtId?: number;
-    limit?: number;
-  }): Promise<LocationEntity[]> {
-    const { keyword, provinceId, cityId, districtId, limit = 10 } = params;
-
-    const queryBuilder = this.locationRepository
-      .createQueryBuilder('location')
-      .leftJoinAndSelect('location.province', 'province')
-      .leftJoinAndSelect('location.city', 'city')
-      .leftJoinAndSelect('location.district', 'district')
-      .where('location.isDeleted = :isDeleted', { isDeleted: 0 })
-      .andWhere('location.isDisabled = :isDisabled', { isDisabled: DisabledStatus.ENABLED });
-
-    // 关键词搜索
-    if (keyword) {
-      queryBuilder.andWhere('(location.name LIKE :keyword OR location.address LIKE :keyword)', {
-        keyword: `%${keyword}%`
-      });
-    }
-
-    // 省份筛选
-    if (provinceId) {
-      queryBuilder.andWhere('location.provinceId = :provinceId', { provinceId });
-    }
-
-    // 城市筛选
-    if (cityId) {
-      queryBuilder.andWhere('location.cityId = :cityId', { cityId });
-    }
-
-    // 区县筛选
-    if (districtId) {
-      queryBuilder.andWhere('location.districtId = :districtId', { districtId });
-    }
-
-    // 限制结果数量
-    queryBuilder.take(limit);
-
-    return await queryBuilder.getMany();
-  }
-
-  /**
-   * 根据省市区ID获取地点
-   */
-  async findByAreaIds(params: {
-    provinceId?: number;
-    cityId?: number;
-    districtId?: number;
-  }): Promise<LocationEntity[]> {
-    const { provinceId, cityId, districtId } = params;
-
-    const queryBuilder = this.locationRepository
-      .createQueryBuilder('location')
-      .leftJoinAndSelect('location.province', 'province')
-      .leftJoinAndSelect('location.city', 'city')
-      .leftJoinAndSelect('location.district', 'district')
-      .where('location.isDeleted = :isDeleted', { isDeleted: 0 })
-      .andWhere('location.isDisabled = :isDisabled', { isDisabled: DisabledStatus.ENABLED });
-
-    if (provinceId) {
-      queryBuilder.andWhere('location.provinceId = :provinceId', { provinceId });
-    }
-
-    if (cityId) {
-      queryBuilder.andWhere('location.cityId = :cityId', { cityId });
-    }
-
-    if (districtId) {
-      queryBuilder.andWhere('location.districtId = :districtId', { districtId });
-    }
-
-    return await queryBuilder.getMany();
-  }
-}