feat: add memory cache to boost performance (#2620)

* feat: add memory cache to boost performance

* fix: tests

* fix: logging

* fix: missing commented stuff
This commit is contained in:
Jérémy M
2023-11-21 18:29:31 +01:00
committed by GitHub
parent 74e0122294
commit dd125ddfcc
27 changed files with 458 additions and 17 deletions

View File

@ -12,6 +12,7 @@ import { RefreshToken } from 'src/core/refresh-token/refresh-token.entity';
export class TypeORMService implements OnModuleInit, OnModuleDestroy {
private mainDataSource: DataSource;
private dataSources: Map<string, DataSource> = new Map();
private isDatasourceInitializing: Map<string, boolean> = new Map();
constructor(private readonly environmentService: EnvironmentService) {
this.mainDataSource = new DataSource({
@ -35,23 +36,46 @@ export class TypeORMService implements OnModuleInit, OnModuleDestroy {
public async connectToDataSource(
dataSource: DataSourceEntity,
): Promise<DataSource | undefined> {
// Wait for a bit before trying again if another initialization is in progress
while (this.isDatasourceInitializing.get(dataSource.id)) {
await new Promise((resolve) => setTimeout(resolve, 10));
}
if (this.dataSources.has(dataSource.id)) {
return this.dataSources.get(dataSource.id);
}
this.isDatasourceInitializing.set(dataSource.id, true);
try {
const dataSourceInstance = await this.createAndInitializeDataSource(
dataSource,
);
this.dataSources.set(dataSource.id, dataSourceInstance);
return dataSourceInstance;
} finally {
this.isDatasourceInitializing.delete(dataSource.id);
}
}
private async createAndInitializeDataSource(
dataSource: DataSourceEntity,
): Promise<DataSource> {
const schema = dataSource.schema;
const workspaceDataSource = new DataSource({
url: dataSource.url ?? this.environmentService.getPGDatabaseUrl(),
type: 'postgres',
logging: ['query'],
logging: this.environmentService.isDebugMode()
? ['query', 'error']
: ['error'],
schema,
});
await workspaceDataSource.initialize();
this.dataSources.set(dataSource.id, workspaceDataSource);
return workspaceDataSource;
}