Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS sequelize Do Not Close Automatically when the Script Done

I am facing some problem with my DB connection design with sequelize.js. What I want to achieve is to have a centralize connection and configuration files for my application DB connection. Therefore I have created a file name database.js as below.

const Sequelize = require("sequelize");
const dbConfig = require("../../config/database.json");

const db = {};

sequelize = new Sequelize({
  dialect: dbConfig.dialect,
  database: dbConfig.database,
  username: dbConfig.username,
  password: dbConfig.password,
  host: dbConfig.host,
  port: dbConfig.port,
  operatorsAliases: false,
  logging: false,

  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

db.Sequelize = Sequelize;
db.sequelize = sequelize;

module.exports = db;

If there is any scripts going to use database, I just have to require the database.js file. However, there is a problem when my script is finished, the process is not exiting (terminal hang there) because of the sequelize connection is not close.

I have tried to call the close function on the finally block but this causing others query script not working (if I call it on every query block) due to the fact that they are sharing same instant. Once the first query done, then the connection will be closed.

sequelize
  .query("SELECT * FROM users WHERE id = ?", {
    replacements: [userId],
    type: sequelize.QueryTypes.SELECT,
    model: User,
    mapToModel: true
  })
  .then(users => {    
    console.log(users);
  })
  .finally(() => {
    sequelize.close();
  });

I can close the connection on the last query, but it is stupid that whenever I got a new query that will need to execute at last, I will have to move the close to the new query block.

I am looking for a clean code that can help to maintain DB connection and also able to automatic close the connection when all scripts are executed.

like image 642
overshadow Avatar asked Nov 07 '22 21:11

overshadow


1 Answers

sequelize.close() returns a promise so use async function and call await sequelize.close()

like image 152
Charan Sai Avatar answered Nov 14 '22 21:11

Charan Sai