0
votes

I have a table I want to load once right after Nest starts and the database is connected I can't seem to find an event for TypeORM for db - is Connected, and when I try getConnection I get a warning, and right now I solved this in a poor timeout po

const f = () => {
    const con = getConnection();
    if (con.isConnected) {
        console.log('connected');
        // this is where the table load will take place
    } else {
        console.error('not connected');
        setTimeout(() => {
            f();
        }, 200);
    }
};
f();

that results in "ConnectionNotFoundError: Connection "default" was not found."

so I wonder if there's anyway around it ?

2

2 Answers

1
votes

You should use createConnection() instead of getConnection().

getConnection() gets a connection already created using createConnection().

createConnection() returns a promise which you can await, or you can call your callback with createConnection().then(...). The promise resolves after the connection successfully connects, or rejects if it fails to connect.

See TypeOrm connection API for more.

0
votes

just in case someone else needs that - the answer (for me) was in NestJS - using OnApplicationBootstrap which led to this code running after everything was initialized

@Injectable()
export class ConfigurationService implements OnApplicationBootstrap {
  async onApplicationBootstrap() {
    const all = await Configuration.find();
    console.log('all?', all.length);
  }
}