soccerway
soccerway

Reputation: 11931

How do we close the database `connection` in sequelize

How do we close the database connection in the below app.post. Do sequelize will automatically taken care of it ?

server.js

const sequelize = new Sequelize(DB_NAME, DB_USERNAME, DB_PASSWORD, {
  host: DB_HOST,
  dialect: DB_DIALECT,
  pool: DB_POOL,
  port: DB_PORT
});

const Availability = availabilitySchema(sequelize, DataTypes);

app.post('/service/availability', async (req, res) => {
  try {
    const userEmail = req.query.email;
    const dailyStatus =  req.body.dailystatus;
    var playerData = {email:userEmail, dailystatus: dailyStatus};
    const playerDailyStatus = await Availability.create(playerData);
    res.status(200).json({ success: true });
  } catch (e) {
    res.status(500).json({ message: e.message });
  }
});

Upvotes: 0

Views: 1753

Answers (1)

Caius Jard
Caius Jard

Reputation: 74595

As i understand it (and I only started looking at sequelize yesterday - comments if I'm wrong, please) Sequelize pools its connections, so there isn't really anything for you to close; it opens and closes connections as necessary much like any other ORM, and mostly those connections are open and live in a pool, are leased from the pool and do some work, then are returned to the pool. You can configure the pool options (looks like you already have) if you want to limit the number of concurrently open connections to your DB but if you're looking in your DB manager and seeing "omg, my sequelize appp has 5 open connections.. now it has 10.. now 15!" that's just how it is; it opens as many connections as necessary (up to the max) to service the workload and leaves them open because it's a huge waste of time to actually open (TCP connect) and close them constantly (TCP disconnect).

When using an ORM you don't micromanage the connections, you just carry out queries using the modeled objects and let the ORM deal with the low level stuff (opening and closing a connection is a level below crafting the SQL to run, and you hand that off to the ORM too). Even in something you've been used to elsewhere, like C# new SqlConnection("connstr").Open() might not actually be opening a TCP cnnection to the DB and closing it; it's probably just leasing and returning to a pool and the underlying framework manages the actual TCP connections and their state

Upvotes: 2

Related Questions