import { ConnectionNotFoundError , TransactionNotFoundError } from '@/infra/repos/postgres/helpers' ; import { DbTransaction } from '@/application/contracts' ; import { createConnection , getConnection , getConnectionManager , ObjectType , QueryRunner , Repository , Connection , getRepository } from 'typeorm' ; export class PgConnection implements DbTransaction { private static instance ? : PgConnection ; private query ? : QueryRunner ; private connection ? : Connection ; private constructor ( ) { } static getInstance ( ) { if ( PgConnection . instance === undefined ) PgConnection . instance = new PgConnection ( ) ; return PgConnection . instance ; } async connect ( ) { this . connection = getConnectionManager ( ) . has ( 'default' ) ? getConnection ( ) : await createConnection ( ) ; } async disconnect ( ) { if ( this . connection === undefined ) throw new ConnectionNotFoundError ( ) ; await getConnection ( ) . close ( ) ; this . query = undefined ; this . connection = undefined ; } async openTransaction ( ) { if ( this . connection === undefined ) throw new ConnectionNotFoundError ( ) ; this . query = this . connection . createQueryRunner ( ) ; await this . query . startTransaction ( ) ; } async closeTransaction ( ) { if ( this . query === undefined ) throw new TransactionNotFoundError ( ) ; await this . query . release ( ) ; } async commit ( ) { if ( this . query === undefined ) throw new TransactionNotFoundError ( ) ; await this . query . commitTransaction ( ) ; } async rollback ( ) { if ( this . query === undefined ) throw new TransactionNotFoundError ( ) ; await this . query . rollbackTransaction ( ) ; } getRepository < Entity > ( entity ) { if ( this . connection === undefined ) throw new ConnectionNotFoundError ( ) ; if ( this . query !== undefined ) return this . query . manager . getRepository ( entity ) ; return getRepository ( entity ) ; } }