/**
* Necessary Imports for Server
* - express: Framework for building web applications in Node.js.
* - bodyParser: Middleware for parsing incoming request bodies.
* - app: Instance of the Express application.
* - port: Port number on which the server will listen for incoming requests.
* - cors: Middleware for enabling Cross-Origin Resource Sharing (CORS).
* - Pool: Class from the pg library for managing PostgreSQL connections.
* - dbConfig: Configuration settings for connecting to the PostgreSQL database.
* - pool: Instance of the PostgreSQL connection pool.
* - apiRouter: Router handling API endpoints.
* - errorHandler: Middleware for handling errors in the application.
* - passport: Middleware for handling secure authentication.
* @module Server
*/
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
require('dotenv').config();
const requestLogger = require('./middleware/logging');
const cors = require('cors');
const { Pool } = require('pg');
const { pool } = require('./dbConfig');
const apiRouter = require('./api');
const errorHandler = require('./middleware/errorHandler');
const passport = require('./middleware/passportMiddleware');
const session = require('express-session');
const swagger = require('./swagger');
const port = process.env.PORT;
// Initialize session middleware with environment variables
app.use(session({
secret: process.env.SESSION_SECRET, // Set session secret using environment variable
resave: false, // Prevents session data from being saved on every request
saveUninitialized: true // Ensures a session is saved, even if it's empty
}));
app.use(bodyParser.json()); // enable middleware for parsing incoming request bodies
app.use(cors()); // Enable CORS for all routes
app.use(passport.initialize()); // Initialize Passport.js middleware
app.use(requestLogger); // Initialize requestLogger middleware
app.use('/api', apiRouter); // Enable api routing for backend endpoints defined in api.js
app.use(errorHandler); // Enable error Handling
app.use('/docs', swagger);
// Test the DB Connection
pool.query('SELECT version()', (err, result) => {
if (err) {
console.error('Error executing query', err);
} else {
console.log('PostgreSQL version:', result.rows[0].version);
}
});
// Handles if there are any connection errors
pool.on('error', (err, client) => {
console.error('Unexpected error on idle client', err);
process.exit(-1);
});
/**
- Graceful Shutdown: Close the pool on SIGINT signal
*/
process.on('SIGINT', () => {
pool.end(() => {
console.log('Pool has ended');
process.exit(0);
});
});
// Start the server
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});