2024-09-24 17:19:49 +05:30
|
|
|
import { Sequelize } from 'sequelize';
|
|
|
|
|
import dotenv from 'dotenv';
|
2024-10-09 23:07:09 +05:30
|
|
|
import setupAssociations from '../models/associations';
|
2024-09-24 17:19:49 +05:30
|
|
|
|
|
|
|
|
dotenv.config();
|
|
|
|
|
const sequelize = new Sequelize(
|
2024-09-25 18:08:35 +05:30
|
|
|
`postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`,
|
2024-09-24 17:24:24 +05:30
|
|
|
{
|
2024-09-25 18:08:19 +05:30
|
|
|
host: 'localhost',
|
2024-09-24 17:24:24 +05:30
|
|
|
dialect: 'postgres',
|
|
|
|
|
logging: false,
|
|
|
|
|
}
|
2024-09-24 17:19:49 +05:30
|
|
|
);
|
|
|
|
|
|
|
|
|
|
export const connectDB = async () => {
|
2024-09-24 17:24:24 +05:30
|
|
|
try {
|
|
|
|
|
await sequelize.authenticate();
|
|
|
|
|
console.log('Database connected successfully');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Unable to connect to the database:', error);
|
|
|
|
|
}
|
2024-09-24 17:19:49 +05:30
|
|
|
};
|
|
|
|
|
|
2024-09-24 18:00:25 +05:30
|
|
|
export const syncDB = async () => {
|
|
|
|
|
try {
|
2024-10-09 23:07:09 +05:30
|
|
|
//setupAssociations();
|
2024-09-24 18:00:38 +05:30
|
|
|
await sequelize.sync({ force: false }); // force: true will drop and recreate tables on every run
|
|
|
|
|
console.log('Database synced successfully!');
|
2024-09-24 18:00:25 +05:30
|
|
|
} catch (error) {
|
2024-09-24 18:00:38 +05:30
|
|
|
console.error('Failed to sync database:', error);
|
2024-09-24 18:00:25 +05:30
|
|
|
}
|
2024-09-24 18:00:38 +05:30
|
|
|
};
|
|
|
|
|
|
2024-09-24 18:00:25 +05:30
|
|
|
|
2024-09-24 17:19:49 +05:30
|
|
|
export default sequelize;
|