I'm trying to use nextjs and sequelize together. It works but I have a problem with each request from the database it opens a connection for DB. I have a Db class and export an instance from this class then use it wherever I need.
import { FindOptions, Model, ModelCtor, Sequelize } from 'sequelize'
import { initModels, Models } from './models';
class Db {
connection: Sequelize | null = null;
constructor() {
this.connection = this.connectDb()
initModels(this.connection)
}
retrieveAll(model: ModelCtor<Model<any, any>>, options: FindOptions<any> = {}) {
return model?.findAll(options);
}
retrieve(model: ModelCtor<Model<any, any>>, options: FindOptions<any> = {}) {
return model?.findOne(options);
}
connectDb() {
const dbName = process.env.DB_NAME
const dbHost = process.env.DB_HOST
const dbUser = process.env.DB_USER as string
const dbPassword = process.env.DB_PASSWORD
const sequelize = new Sequelize({
dialect: 'postgres',
host: dbHost,
port: 5432,
database: dbName,
username: dbUser,
password: dbPassword,
pool: {
max: 5,
idle: 86400000,
}
});
try {
sequelize.authenticate();
console.log('Connection has been established successfully.');
return sequelize;
} catch (error) {
console.error('Unable to connect to the database:', error);
return null;
}
}
closeConnectionDb() {
this.connection?.close()
}
}
export const db = new Db();
For example, I make a query database for login then on homepage I get merchant list from the database. I see two times "Connection has been established successfully.". How can I solve this problem? By the way, it works very well in the production server. I think it's about module caching but I'm not sure.
console.log('Disconnected')log inside thecloseConnectionDbfunction, do you see that two times?