import { DataSource, EntityTarget, ObjectLiteral, Repository } from 'typeorm'; import { TenantContextService } from '@it0/common'; export abstract class TenantAwareRepository { constructor( protected readonly dataSource: DataSource, protected readonly entity: EntityTarget, ) {} protected async getRepository(): Promise> { const schema = TenantContextService.getSchemaName(); const queryRunner = this.dataSource.createQueryRunner(); await queryRunner.query(`SET search_path TO "${schema}", public`); return queryRunner.manager.getRepository(this.entity); } async findById(id: string): Promise { const repo = await this.getRepository(); return repo.findOneBy({ id } as any); } async save(entity: T): Promise { const repo = await this.getRepository(); return repo.save(entity); } async findAll(): Promise { const repo = await this.getRepository(); return repo.find(); } async remove(entity: T): Promise { const repo = await this.getRepository(); return repo.remove(entity); } }