I'm currently working on a project using PostgreSQL with Sequelize and Umzug in an ES6+ environment. However, I've encountered challenges with setting up the environment as I want to use ES6+. I'm seeking guidance on the best practices and potential solutions for integrating these technologies seamlessly.
I tried below ones:
This is my config.js
// config/config.js
require('dotenv').config(); // Load environment variables
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: "postgres"
},
test: {
dialect: "postgres"
},
production: {
dialect: "postgres"
}
};
This is my database.js
// config/database.js
import Sequelize from 'sequelize';
import dotenv from 'dotenv';
// Load environment variables
dotenv.config();
const { DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME } = process.env;
if (!DB_HOST || !DB_PORT || !DB_USER || !DB_PASSWORD || !DB_NAME || DB_NAME.trim() === '') {
throw new Error('Missing or invalid database environment variables.');
}
const sequelize = new Sequelize({
dialect: 'postgres',
host: DB_HOST,
port: DB_PORT,
username: DB_USER,
password: DB_PASSWORD,
database: DB_NAME,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false, // This line is particularly important for local development
},
},
pool: {
max: 5, // Maximum connections
min: 0, // Minimum connections
acquire: 30000,
idle: 10000, // Idle timeout in milliseconds
},
});
const connectToPostgres = async () => {
try {
await sequelize.authenticate();
console.log('Database connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error.message);
// Optionally: Handle specific error scenarios (e.g., different error codes)
}
};
const closeConnection = async () => {
try {
await sequelize.close();
console.log('Database connection closed');
} catch (error) {
console.error('Error closing database connection:', error.message);
}
};
export { sequelize, connectToPostgres, closeConnection };
// migrations/umzug.js
// migrations/umzug.mjs
import { Umzug, SequelizeStorage } from 'umzug';
import sequelize from '../config/database.mjs'; // Importing Sequelize instance
import { fileURLToPath } from 'url'; // Importing the fileURLToPath function from the 'url' module
import path, { dirname } from 'path'; // Importing the path and dirname functions from the 'path' module
// Convert import.meta.url to a file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Define the path to the migrations directory
const migrationsPath = path.join(__dirname, 'migrations');
// Create Umzug instance
const migrator = new Umzug({
migrations: {
glob: ['*.{js,cjs,mjs}', { cwd: migrationsPath }],
},
context: sequelize.getQueryInterface(),
storage: new SequelizeStorage({
sequelize,
}),
logger: console,
});
// Run Umzug CLI
migrator.runAsCLI();