feat: basic db connection
This commit is contained in:
@@ -1,7 +1,26 @@
|
||||
const { Pool } = require("pg");
|
||||
import { Sequelize } from 'sequelize';
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
// Initialize Sequelize
|
||||
const db = new Sequelize({
|
||||
dialect: 'postgres',
|
||||
host: process.env.DB_HOST || 'localhost',
|
||||
port: parseInt(process.env.DB_PORT || '5432'),
|
||||
database: process.env.DB_NAME || 'postgres',
|
||||
username: process.env.DB_USER || 'postgres',
|
||||
password: process.env.DB_PASSWORD || 'pass',
|
||||
logging: false, // Disable logging in production
|
||||
});
|
||||
|
||||
module.exports = pool;
|
||||
// Test the connection
|
||||
async function testConnection() {
|
||||
try {
|
||||
await db.authenticate();
|
||||
console.log('✅ Database connection established.');
|
||||
} catch (err) {
|
||||
console.error('❌ Unable to connect to the database:', err);
|
||||
process.exit(1); // Exit if DB connection fails
|
||||
}
|
||||
}
|
||||
|
||||
// Export Sequelize instance and models
|
||||
export { db, testConnection };
|
||||
|
||||
@@ -2,6 +2,7 @@ import express, { Express, Request, Response } from "express";
|
||||
import cors from "cors";
|
||||
import * as dotenv from "dotenv";
|
||||
import transactionsRouter from './routes/transactions';
|
||||
import { db, testConnection } from "./db";
|
||||
|
||||
|
||||
dotenv.config();
|
||||
@@ -17,6 +18,19 @@ app.get("/api/health", (req: Request, res: Response) => {
|
||||
app.use('/api/transactions', transactionsRouter);
|
||||
|
||||
const PORT: number = parseInt(process.env.PORT as string) || 3000;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
|
||||
// Start server after DB connection is established
|
||||
async function startServer() {
|
||||
await testConnection(); // Test DB connection first
|
||||
|
||||
// Sync models (use migrations in production!)
|
||||
await db.sync({ alter: true }); // Use { force: true } to drop and recreate tables (development only!)
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Backend Server running on http://localhost:${PORT}`);
|
||||
});
|
||||
}
|
||||
startServer().catch((err) => {
|
||||
console.error('Failed to start server:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user