import { Injectable } from '@nestjs/common'; import { BaseCrudService } from '../common/base-crud.service.js'; import { PrismaService } from '../prisma/prisma.service.js'; import { RedisService } from '../common/redis/redis.service.js'; import { getRequestContext } from '../common/context/request-context.js'; import { CreateResourceDto, UpdateResourceDto } from './dto.js'; @Injectable() export class ResourcesService extends BaseCrudService { constructor( prisma: PrismaService, private readonly redis: RedisService, ) { super(prisma, 'resource'); } async createResource(dto: CreateResourceDto) { const created = await this.create({ ...dto }); await this.clearPermCache(); return created; } async updateResource(id: string, dto: UpdateResourceDto) { const updated = await this.update(id, { ...dto }); await this.clearPermCache(); return updated; } async softRemove(id: string) { const removed = await super.softRemove(id); await this.clearPermCache(); return removed; } /** 批量删除:逐个软删(回收 code),最后统一清权限缓存。 */ async batchDelete(ids: string[]) { const failed: string[] = []; for (const id of ids) { try { await super.softRemove(id); } catch { failed.push(id); } } await this.clearPermCache(); return { total: ids.length, success: ids.length - failed.length, failed }; } /** 资源变更(含停用/删除)影响权限码聚合,清该租户全部权限缓存。 */ private async clearPermCache(): Promise { const ctx = getRequestContext(); if (ctx) await this.redis.delByPrefix(`perm:${ctx.tenantCode}:`); } }