import { DataSource } from 'typeorm'; import { RoleMt } from '../entities/role.entity'; import { ConcreteCrudService } from '@d8d/shared-crud'; export class RoleServiceMt extends ConcreteCrudService { constructor(dataSource: DataSource) { super(RoleMt, { userTracking: { enabled: false }, tenantOptions: { enabled: true, tenantIdField: 'tenantId', autoExtractFromContext: true } }); } /** * 根据角色名获取角色(自动添加租户过滤) */ async getRoleByName(name: string, tenantId?: number): Promise { try { const where: any = { name }; // 如果提供了租户ID,添加租户过滤 if (tenantId !== undefined) { where.tenantId = tenantId; } const roles = await this.repository.find({ where }); return roles.length > 0 ? roles[0] : null; } catch (error) { console.error('Error getting role by name:', error); throw new Error('Failed to get role by name'); } } /** * 检查角色是否拥有指定权限 */ async hasPermission(roleId: number, permission: string, tenantId?: number): Promise { try { const role = await this.getById(roleId, [], { tenantId }); if (!role) return false; return role.permissions.includes(permission); } catch (error) { console.error('Error checking permission:', error); throw new Error('Failed to check permission'); } } /** * 获取所有角色(自动添加租户过滤) */ async getRoles(tenantId?: number): Promise { try { const where: any = {}; // 如果提供了租户ID,添加租户过滤 if (tenantId !== undefined) { where.tenantId = tenantId; } return await this.repository.find({ where }); } catch (error) { console.error('Error getting roles:', error); throw new Error(`Failed to get roles: ${error instanceof Error ? error.message : String(error)}`); } } /** * 根据ID获取角色(重写以添加租户过滤) */ async getById(id: number, relations: string[] = [], options?: { tenantId?: number }): Promise { try { const where: any = { id }; // 如果提供了租户ID,添加租户过滤 if (options?.tenantId !== undefined) { where.tenantId = options.tenantId; } return await this.repository.findOne({ where, relations }); } catch (error) { console.error('Error getting role by id:', error); throw new Error('Failed to get role by id'); } } /** * 更新角色(重写以添加租户过滤) */ async update(id: number, data: Partial, options?: { tenantId?: number }): Promise { try { // 首先验证角色是否存在且属于指定租户 const existingRole = await this.getById(id, [], options); if (!existingRole) return null; // 更新角色 await this.repository.update(id, data); // 返回更新后的角色 return await this.getById(id, [], options); } catch (error) { console.error('Error updating role:', error); throw new Error('Failed to update role'); } } /** * 删除角色(重写以添加租户过滤) */ async delete(id: number, options?: { tenantId?: number }): Promise { try { // 首先验证角色是否存在且属于指定租户 const existingRole = await this.getById(id, [], options); if (!existingRole) return false; // 删除角色 const result = await this.repository.delete(id); return result.affected === 1; } catch (error) { console.error('Error deleting role:', error); throw new Error('Failed to delete role'); } } }