Snai3i-LandingPage-FormBuilder / backend / src / app.ts
app.ts
Raw
import express, { Request, Response, NextFunction } from 'express';
import cors from 'cors';
import { DevCors, ProductionCors } from './utils/cors';
import cookieParser from 'cookie-parser';
import { CLIENT_URL, InDev, PORT } from './config/env';
import { ErrorResponse, SuccessResponse } from './utils/response';
import { HttpCodes } from './config/errors';
import setRouters from './routes/index';
import { errorMiddleware } from './middlewares/errorMiddleware';
import connectDB from './config/database';
import Logger from './utils/logger';
import loggerMiddleware from './middlewares/loggerMiddleware';

export const app = express();

app.use(InDev ? cors(DevCors) : cors(ProductionCors));

// Parse incoming request bodies as URL-encoded data.
app.use(express.urlencoded({ extended: true }));

// Parse incoming request bodies as JSON.
app.use(express.json());

// cookie-parser
app.use(cookieParser());

// Logger Middleware
app.use(loggerMiddleware);

// Set up general routes using the `setRouters` function.
setRouters(app);

//testing
app.get('/', (req: Request, res: Response, next: NextFunction) => {
  return SuccessResponse(res, HttpCodes.Accepted.code, 'Api is working');
});

app.use('*', (req: Request, res: Response, next: NextFunction) => {
  return ErrorResponse(
    res,
    HttpCodes.NotFound.code,
    HttpCodes.NotFound.message
  );
});

// Mount the error handling middleware
app.use(errorMiddleware);

// Connect to the database and then start the server.
connectDB().then(async () => {
  app.listen(PORT, () => {
    // Display server and backend URLs upon successful server start.
    const port_msg = `Server running on port: ${PORT}.`;
    const url_msg = `The backend is accessible at: ${CLIENT_URL}.`;
    const max_length = Math.max(url_msg.length, port_msg.length) + 4;
    const n = Math.floor((max_length - port_msg.length) / 2);
    const m = Math.floor((max_length - url_msg.length) / 2);

    Logger.log(' ' + '-'.repeat(max_length));
    Logger.log(`|${' '.repeat(n)}${port_msg}${' '.repeat(n)} |`);
    Logger.log(`|${' '.repeat(m)}${url_msg}${' '.repeat(m)}|`);
    Logger.log(' ' + '-'.repeat(max_length));
  });
});