0

I am trying to inject Typeform data source into my Student repository. container setup

container.bind<PGContext>(TYPES.PGContext).to(PGContext);

Pg context class, connect called in index.js

 @injectable()
 export class PGContext {
   public _pg: DataSource;
  public manager: any;
  constructor() {
    console.log('Db context initialized');
  }

   async connect() {
     console.log('database connected!!');
     try {
       this._pg = new DataSource({
         type: 'postgres',
        host: 'localhost',
         port: 5432,
         username: 'admin',
         password: 'admin',
         database: 'postgres',
         migrationsTableName: 'migrations',
         synchronize: true,
         migrations: ['./migrations/**/*.ts'],
         entities: [Student],
       });
       console.log(this._pg, 'PG context...');
      await this._pg.initialize().then((res) => {
        this.manager = res;
      });
    } catch (error) {
      console.log(error);
    }
   }
 }

I am trying to inject the database connection into this repository but I am getting this.pg as undefined

@injectable()
export class StudentRepository implements IRepository<any> {
  public pg: DataSource;

   constructor(@inject(TYPES.PGContext) pgContext: PGContext) {
     // this.pg = pgContext.;
     console.log(pgContext.manager, 'STUDENT reoi');
     this.pg = pgContext._pg;
     console.log(this.pg);
   }

  async find(): Promise<Student[]> {
    this.pg.manager.find(Student)
    // this is undefined 

  }

I am trying to inject DB context into the student repository, but this.pg is undefined.

I am calling connect in index.js

const pgContext = container.get<PGContext>(TYPES.PGContext);
pgContext.connect()
amit rai
  • 5
  • 2
  • 4

0 Answers0