Skip to content

Commit

Permalink
Revamped the codes
Browse files Browse the repository at this point in the history
  • Loading branch information
kyrea committed Dec 19, 2023
1 parent 0d31af2 commit 0cd0660
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 92 deletions.
71 changes: 50 additions & 21 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,69 @@
/*** Importing necessary modules ***/
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';

// Import custom error handlers and logger
/*** Importing custom error handlers and logger middleware ***/
import {
handler404,
errorsLogger,
errorsHandler,
} from './handlers/errors/index.js';
import { ipLogger } from './handlers/logger/ip.js';
import routes from './routes.js';

// Express APP
handle404, /*** @params: req, res, next ***/
logErrors, /*** @params: err, req, res, next ***/
errorHandler, /*** @params: err, req, res, next ***/
} from './middlewares/errors.js';
import { logIP } from './middlewares/logger.js';
import routesV3 from './routes/v3/index.js';
import routesV4 from './routes/v4/index.js';

/*** Creating an instance of Express ***/
const app = express();

// Enable CORS for all routes
/*** Enabling CORS for all routes ***/
app.use(cors());

// Trust the first proxy (when running behind a reverse proxy like Nginx)
/*** Trusting the first proxy (when running behind a reverse proxy like Nginx) ***/
app.set('trust proxy', 1);

// Middleware to parse JSON-encoded bodies
/*** Middleware to parse JSON-encoded bodies ***/
app.use(express.json());

// Middleware to parse URL-encoded bodies
/*** Middleware to parse URL-encoded bodies ***/
app.use(express.urlencoded({ extended: true }));

// Logger middleware
// Uncomment the following block if you want to enable IP logging
/*** Logger middleware ***/
/**
* @middleware
* @description Enables IP logging for incoming requests.
* @function
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @param {Function} next - Express next middleware function.
*/
if (process.env.LOGGER === 'true') {
app.use(ipLogger);
app.use(logIP);
}

// Custom API routes
app.use(routes);
/*** Middleware to parse the request body ***/
app.use(bodyParser.json());

/*** Custom API routes ***/
app.use('/api/v4', routesV4);
app.use(routesV3);

// Error handling middleware
app.use(handler404, errorsLogger, errorsHandler);
/**
* @apiMiddleware
* @function
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @param {Function} next - Express next middleware function.
*
* @apiSuccess {Object[]} response - Response data.
*
* @apiError {BadRequest} BadRequest - Invalid request parameters.
* @apiError {Unauthorized} Unauthorized - Only authenticated users can access the data.
* @apiError {Forbidden} Forbidden - Only authorized users can access the data.
* @apiError {NotFound} NotFound - The requested resource was not found.
* @apiError {InternalServerError} InternalServerError - Something went wrong on the server.
*/
app.use(handle404, logErrors, errorHandler);

export default app;
/*** Exporting the Express app instance ***/
export default app;
93 changes: 22 additions & 71 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
/* eslint-disable no-console */

// Importing configuration modules
import './modules/config/config.js';
import 'dotenv/config';

// Importing external modules
import mongoose from 'mongoose';
import chalk from 'chalk';
import app from './app.js';

// PORT
// Setting up the server port
const PORT = process.env.PORT || 4000;

// NODE ENV LOGGER
/*
Logging developer mode information for the Node environment
*/
if (process.env.NODE_ENV === 'development') {
console.log(
`${chalk.yellow(
'[DEBUG]'
)} You've enabled developer mode. Now your console will be dirty.`
);
console.log(`${chalk.yellow('[DEBUG]')} Developer mode enabled. Console logging is active.`);
}

// Connect to the database, then start the Express server
/*
Connect to the MongoDB database, then start the Express server
*/
mongoose
.connect(process.env.MONGODB_URI, {
useUnifiedTopology: true,
Expand All @@ -26,69 +30,16 @@ mongoose
useFindAndModify: false,
})
.then(() => {
app.listen(PORT, () =>
console.log(
`${chalk.green(
'[SUCCESS]'
)} API is running on: http://localhost:${PORT}/api`
)
);
/*
Starting the Express server and logging success message
*/
app.listen(PORT, () => {
console.log(`${chalk.green('[SUCCESS]')} API is running on: http://localhost:${PORT}/api`);
});
})
.catch((error) => {
.catch(error => {
/*
Logging errors during database connection
*/
console.error(error);
});

// const Users = require('./models/schemas/Users')

// // function to reset token of every user once every 24 hours
// const quotoInterval = setInterval(() => {
// // query and update all users req_quoto to 250
// Users.updateMany({}, { $set: { req_quoto: 25 } }, (err, res) => {
// if (err) console.log(err)
// console.log(res)
// })
// }, 5000)




// const Stats = require('./models/schemas/Stat');

// function to reset daily_requests to 0 every 24 hours at 00:00 AM GMT+0
// setInterval(() => {

// Stats.findByIdAndUpdate(
// { _id: "systemstats" },
// { $set: { daily_requests: 0 } }
// )
// .then(() => {
// console.log(`${chalk.green('[SUCCESS]')} Daily requests reset to 0`)
// })
// .catch(error => {
// console.error(error)
// })
// }, 86400000)


// a interval to update the daily_requests at 00:00 AM GMT+0
// setInterval(() => {
// Stats.findByIdAndUpdate(
// { _id: "systemstats" },
// { $inc: { daily_requests: 1 } }
// )
// .then(() => {
// console.log(`${chalk.green('[SUCCESS]')} Daily requests incremented`)
// })
// .catch(error => {
// console.error(error)
// })
// }, 1000)



// function to reset daily_requests to 0 every 24 hours at 00:00 AM GMT+0 using unix timestamp





0 comments on commit 0cd0660

Please sign in to comment.