6

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.

1
  • Did you manage to find the solution to this. Also are you using v5.0 of Sequelize? Would you now recommend manually closing it? Commented Dec 2, 2019 at 7:43

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.