I am using Sequelize
with Node.js
and TypeScript
to connect to a PostgreSQL
database. I want to export and import a single Sequelize
instance throughout my application, so that I have a single connection to the database.
I have seen many examples where the Sequelize
instance is exported directly from a module, like this:
import { Sequelize } from "sequelize";
import { DB_HOST, DB_NAME, DB_PASSWORD, DB_PORT, DB_USERNAME } from ".";
export default new Sequelize(
`postgres://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`
);
However, I am using a function to get the sequelize
instance instead, like this:
import { Sequelize } from "sequelize";
import { DB_HOST, DB_NAME, DB_PASSWORD, DB_PORT, DB_USERNAME } from ".";
let sequelize: Sequelize;
const getDB = async () => {
if (sequelize) return sequelize;
try {
sequelize = new Sequelize(
`postgres://${DB_USERNAME}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}`
);
await sequelize.authenticate();
console.log(`PostgreSQL is connected to ${DB_HOST}:${DB_PORT}`);
return sequelize;
} catch (error) {
console.error("Unable to connect to the database:", error);
}
};
export default getDB;
I am doing this because I want to make sure that the sequelize
instance is created only once and after the database connection is established. I also want to handle any errors that may occur during the connection.
Is this a good way to export
and import
a single sequelize
instance in Node.js
? Will this create a new instance every time I import it from another module? Or will it reuse the same instance that was created the first time?
For example, if I import and use the sequelize
instance in another module like this:
import getDB from "./db";
const sequelize = await getDB();
const User = sequelize.define("User", { ... });
Will this create a new User
model every time I import it? Or will it use the same User model that was defined the first time?
Any help or advice would be appreciated. Thank you.
2
Answers
I appreciate the explanations from @Seti and @Bergi, they helped me understand the concept of module caching in Node.js. To make it more clear for others who may have the same question, I want to share a simple example that illustrates how Node.js caches modules and exports only one instance of a value.
Let's say we have a file called
foo.js
that exports a variable foo with the value of 1. The file also logs a message "new create" when it is executed.Now, let's say we have another file called
bar.js
that imports the variable foo fromfoo.js
four times using require.If we run
bar.js
, we will see that the message "new create" is logged only once, even though we imported foo four times. This is because Node.js cached the modulefoo.js
after the first time it was loaded, and returned the same instance of foo for every subsequent call to require. This means that we have only one instance of foo throughout our application, and we don't need to use a function to get it.I hope this example makes sense and helps someone who is looking for an answer to this question.
There is not point in makeing this pattern of yours, as if you export anything from module, it becomes singleton of some sort (explained in documentation). Thats why all examples experted sequelize once, and all shared the same database
Source: https://nodejs.org/api/modules.html