import { Init, Inject, Provide } from '@midwayjs/core'; import { BaseService } from '@cool-midway/core'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Repository } from 'typeorm'; import { CardInfoEntity } from '../entity/info'; import { CardPortalService } from './portal'; /** * 名片增删改载荷(Cool CRUD 传入对象、主键或主键列表) */ interface CardModifyRecord { id?: string | number; slug?: string; } /** * 后台名片信息服务 */ @Provide() export class CardInfoService extends BaseService { @InjectEntityModel(CardInfoEntity) cardInfoEntity: Repository; @Inject() cardPortalService: CardPortalService; @Init() async init() { await super.init(); this.setEntity(this.cardInfoEntity); } /** * 新增/修改/删除后清理门户缓存 */ async modifyAfter( data: CardModifyRecord | Array | string | number, type: 'delete' | 'update' | 'add' ): Promise { if (type !== 'add' && type !== 'update' && type !== 'delete') { return; } const keys = this.collectCacheKeys(data); for (const key of keys) { await this.cardPortalService.clearPortalCache(key); } } private collectCacheKeys( data: CardModifyRecord | Array | string | number ): Array { if (data === undefined || data === null || data === '') { return []; } if (typeof data === 'number') { return [data]; } if (typeof data === 'string') { return data .split(',') .map(item => item.trim()) .filter(item => item.length > 0); } if (Array.isArray(data)) { return data.flatMap(item => this.collectCacheKeys(item)); } const keys: Array = []; if (data.id !== undefined && data.id !== null && data.id !== '') { keys.push(data.id); } if (data.slug) { keys.push(data.slug); } return keys; } }