Home > front end >  How to change Postgres connection at run time using Adonis.js?
How to change Postgres connection at run time using Adonis.js?

Time:12-03

I have a stream replication db running and I would like to change the connection to it when the main db fail.

I have set up the connection for both dbs on config/database.ts and tried to use the connection menager event as in adonis docs :

Doc example:

import Database from "@ioc:Adonis/Lucid/Database";

Database.manager.on('db:connection:error', (connection) => {
  console.log(self === connection) // true
})

I tried to use it on start/events.ts but it doesn't recognize the 'on' method.

Property 'on' does not exist on type 'ConnectionManagerContract'

Any idea on how to make this work? Thanks.

CodePudding user response:

It looks like you are trying to use the on method of the ConnectionManagerContract interface in the AdonisJS web framework.

In TypeScript, you cannot call methods on an interface directly. Instead, you can create an instance of the class that implements the interface and call the method on that instance. In the case of the ConnectionManagerContract interface, the implementing class is the ConnectionManager class.

Here is an example of how you can use the on method of the ConnectionManager class to listen for db:connection:error events:

import Database from "@ioc:Adonis/Lucid/Database";

const manager = new Database.manager.ConnectionManager();

manager.on('db:connection:error', (connection) => {
  console.log(connection);
});

You can then use the manager instance to access other methods of the ConnectionManager class, such as create or acquire to create or acquire connections to your databases.

I hope this helps! Let me know if you have any other questions.

  • Related