Authentification in just one file with Sequelize


Authentification in just one file with Sequelize



I am trying to use Sequelize, but I don't know how to figure out that : I want to connect only one time in the start.js, and not in each file.



This is my start.js :


const Sequelize = require("sequelize");

// import environmental variables from our variables.env file
require("dotenv").config({ path: "variables.env" });

// Connect to our Database
const sequelize = new Sequelize(
process.env.DATABASE_NAME,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
host: process.env.DATABASE_HOST,
dialect: "postgres",
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
}
);
// Try to authenticate to our databse
sequelize
.authenticate()
.then(() => {
console.log("🗄 Database connection successful !");
})
.catch(err => {
console.error("🗄 Database connection error...", err);
});

// Start our app!
const app = require("./app");
app.set("port", process.env.PORT || 7777);
const server = app.listen(app.get("port"), () => {
console.log(`🚅 Express running → PORT ${server.address().port}`);
});



And this is a random file (userController.js) when I want to execute a query :


const Sequelize = require("sequelize");
// This is the problem:
const sequelize = new Sequelize; // (.connection() ?)

exports.getUsers = async (req, res) => {
// Query the DB for a list of all users
const users = await sequelize.query("SELECT * FROM profils");
res.send({ users });
};



Thank you for your help ! : )




1 Answer
1



As the reference explains,



Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database if you're connecting to the DB from a single process.



So there should be a single instance, likely defined in a separate module:


const Sequelize = require("sequelize");

module.exports = new Sequelize(...);



that is imported in both middleware and main modules. As the reference also states, authenticate isn't really necessary but can be used to as a step for initialization routine:


authenticate


require("dotenv").config({ path: "variables.env" });

const sequelize = require('./db');

// for testability purposes
module.exports = sequelize
.authenticate()
.then(() => {
// Start our app!
const app = require("./app");
...
// for testability purposes
return app;
})
.catch(err => {
console.error(err);
});






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages