it0/packages/shared/database/src/tenant-aware.repository.ts

37 lines
1.1 KiB
TypeScript

import { DataSource, EntityTarget, ObjectLiteral, Repository } from 'typeorm';
import { TenantContextService } from '@it0/common';
export abstract class TenantAwareRepository<T extends ObjectLiteral> {
constructor(
protected readonly dataSource: DataSource,
protected readonly entity: EntityTarget<T>,
) {}
protected async getRepository(): Promise<Repository<T>> {
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<T | null> {
const repo = await this.getRepository();
return repo.findOneBy({ id } as any);
}
async save(entity: T): Promise<T> {
const repo = await this.getRepository();
return repo.save(entity);
}
async findAll(): Promise<T[]> {
const repo = await this.getRepository();
return repo.find();
}
async remove(entity: T): Promise<T> {
const repo = await this.getRepository();
return repo.remove(entity);
}
}