All files / execution-engine/domain data-source.ts

10% Statements 2/20
0% Branches 0/4
0% Functions 0/6
5.88% Lines 1/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77              1x                                                                                                                                          
import { DataSource } from "typeorm";
import { inject, injectable } from "tsyringe";
import { DatabasesConfig } from "../../config/databases.config.js";
import { ExecutionEntity } from "../entity/execution.entity.js";
import { ProcessedEventEntity } from "../entity/processed.event.entity.js";
 
@injectable()
export class AppDataSourceService {
  public AppDataSource: DataSource;
 
  constructor(
    @inject(DatabasesConfig) private DatabasesConfig: DatabasesConfig,
  ) {
    if (!this.DatabasesConfig.main.connection) {
      throw new Error("DatabasesConfig.db is not defined");
    }
 
    this.AppDataSource = new DataSource({
      type: "postgres",
      host: this.DatabasesConfig.main.connection.host,
      port: this.DatabasesConfig.main.connection.port,
      username: this.DatabasesConfig.main.connection.username,
      password: this.DatabasesConfig.main.connection.password,
      database: "execution",
      synchronize: true,
      logging: true,
      entities: [ExecutionEntity, ProcessedEventEntity],
      subscribers: [],
      migrations: ["src/execution-engine/migration/*.ts"],
      migrationsRun: true,
      extra: {
        max: 20,
        idleTimeoutMillis: 30000,
        connectionTimeoutMillis: 5000,
      },
      ssl: {
        rejectUnauthorized: false,
      },
    });
 
    this.initializeWithRetry(5, 3000)
      .then(() => {
        console.log("Data Source has been initialized!");
      })
      .catch((err) => {
        console.error(
          "All retries failed. Data Source initialization error:",
          err,
        );
      });
  }
 
  private async initializeWithRetry(
    retryCount: number,
    delayMs: number,
  ): Promise<void> {
    for (let i = 1; i <= retryCount; i++) {
      try {
        await this.AppDataSource.initialize();
        return;
      } catch (error) {
        console.error(`Initialization attempt ${i} failed:`, error);
 
        if (i < retryCount) {
          await this.delay(delayMs);
        } else {
          throw error;
        }
      }
    }
  }
 
  private delay(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }
}