import { GenericCrudService } from '@d8d/shared-crud'; import { DataSource, Repository, Like, Not } from 'typeorm'; import { Platform } from '../entities/platform.entity'; export class PlatformService extends GenericCrudService { constructor(dataSource: DataSource) { super(dataSource, Platform); } /** * 创建平台 - 覆盖父类方法,添加名称唯一性检查 */ override async create(data: Partial, userId?: string | number): Promise { // 检查平台名称是否已存在(只检查正常状态的平台) if (data.platformName) { const existingPlatform = await this.repository.findOne({ where: { platformName: data.platformName, status: 1 } }); if (existingPlatform) { throw new Error('平台名称已存在'); } } // 设置默认值 const platformData = { contactPerson: '', contactPhone: '', contactEmail: '', ...data, status: 1, createTime: new Date(), updateTime: new Date() }; return super.create(platformData, userId); } /** * 更新平台 - 覆盖父类方法,添加存在性和名称重复检查 */ override async update(id: number, data: Partial, userId?: string | number): Promise { // 检查平台是否存在(只检查正常状态的平台) const platform = await this.repository.findOne({ where: { id, status: 1 } }); if (!platform) { throw new Error('平台不存在'); } // 检查平台名称是否与其他平台重复(只检查正常状态的平台) if (data.platformName && data.platformName !== platform.platformName) { const existingPlatform = await this.repository.findOne({ where: { platformName: data.platformName, id: Not(id), status: 1 } }); if (existingPlatform) { throw new Error('平台名称已存在'); } } // 设置更新时间 const updateData = { ...data, updateTime: new Date() }; // 现在可以使用父类的update方法,因为主键字段名已改为'id' return super.update(id, updateData, userId); } /** * 删除平台 - 覆盖父类方法,改为软删除(设置status为0) */ override async delete(id: number, userId?: string | number): Promise { // 改为软删除:设置status为0 const result = await this.repository.update({ id }, { status: 0 }); return result.affected === 1; } /** * 获取所有平台(分页) - 自定义方法,返回源服务的格式 */ async findAll(skip?: number, take?: number): Promise<{ data: Platform[], total: number }> { const [data, total] = await this.repository.findAndCount({ where: { status: 1 }, // 只返回正常状态的平台 skip: skip ?? 0, take: take ?? 10, order: { id: 'DESC' } }); return { data, total }; } /** * 按名称搜索平台 - 自定义方法 */ async searchByName(name: string, skip?: number, take?: number): Promise<{ data: Platform[], total: number }> { const [data, total] = await this.repository.findAndCount({ where: { platformName: Like(`%${name}%`), status: 1 // 只返回正常状态的平台 }, skip: skip ?? 0, take: take ?? 10, order: { id: 'DESC' } }); return { data, total }; } /** * 获取单个平台 - 自定义方法 */ async findOne(id: number): Promise { return this.repository.findOne({ where: { id, status: 1 } }); // 只返回正常状态的平台 } }