Changes to index.js structure for middleware

This commit is contained in:
Lucas Patenaude
2024-04-13 14:25:34 -06:00
parent 74d958fa49
commit edd7d17f42
4 changed files with 95 additions and 88 deletions

View File

@@ -78,18 +78,30 @@ app.use(
app.use(express.static(path.join(__dirname, 'resources'))); app.use(express.static(path.join(__dirname, 'resources')));
// ***************************************************** // *****************************************************
// <!-- Section 4 : API Routes --> // <!-- Section 4 : Middleware -->
// *****************************************************
// Importing middleware
const fetchMatchesData = require('./resources/routes/navigation-bar/current-match-information');
const convert_time = require('./resources/js/navigation-bar/scoreboard-header/convert-time');
const fetchLeaguesData = require('./resources/routes/league-pages/get-current-league-information');
// Using middleware
app.use(fetchMatchesData);
app.use(convert_time);
app.use(fetchLeaguesData);
// *****************************************************
// <!-- Section 5 : API Routes -->
// ***************************************************** // *****************************************************
/************************ /************************
Header Scoreboard Routes League Page Routes
*************************/ *************************/
const fetchMatchesData = require('./resources/routes/navigation-bar/current-match-information'); // Import and call generateLeagueRoutes function
app.use(fetchMatchesData); const generateLeagueRoutes = require('./resources/routes/league-pages/generate-league-routes');
generateLeagueRoutes(app);
const convert_time = require('./resources/js/navigation-bar/scoreboard-header/convert-time');
app.use(convert_time);
/************************ /************************
Login Page Routes Login Page Routes
@@ -98,17 +110,16 @@ app.use(convert_time);
// Redirect to the /login endpoint // Redirect to the /login endpoint
app.get('/', (req, res) => { app.get('/', (req, res) => {
res.redirect('/home'); res.redirect('/home');
}); });
// Render login page for /login route // Render login page for /login route
app.get('/login', (req, res) => { app.get('/login', (req, res) => {
res.render('pages/home'); res.render('pages/home');
}); });
// Trigger login form to check database for matching username and password // Trigger login form to check database for matching username and password
app.post('/login', async (req, res) => { app.post('/login', async (req, res) => {
try { try {
// Check if username exists in DB // Check if username exists in DB
const user = await db.oneOrNone('SELECT * FROM users WHERE username = $1', req.body.username); const user = await db.oneOrNone('SELECT * FROM users WHERE username = $1', req.body.username);
@@ -120,7 +131,7 @@ app.get('/', (req, res) => {
// Check if password from request matches with password in DB // Check if password from request matches with password in DB
const match = await bcrypt.compare(req.body.password, user.password); const match = await bcrypt.compare(req.body.password, user.password);
// Check if mathc returns no data // Check if match returns no data
if (!match) { if (!match) {
// Render the login page with the message parameter // Render the login page with the message parameter
return res.render('pages/home', { message: 'Password does not match' }); return res.render('pages/home', { message: 'Password does not match' });
@@ -132,22 +143,20 @@ app.get('/', (req, res) => {
// Redirect user to the home page // Redirect user to the home page
res.redirect('/home'); res.redirect('/home');
} catch (error) { } catch (error) {
// Direct user to login screen if no user is found with matching password // Direct user to login screen if no user is found with matching password
res.redirect('/register'); res.redirect('/register');
} }
}); });
/************************ /************************
Registration Page Routes Registration Page Routes
*************************/ *************************/
// Render registration page for /register route // Render registration page for /register route
app.get('/register', (req, res) => { app.get('/register', (req, res) => {
res.render('pages/register'); res.render('pages/register');
}); });
// Trigger Registration Form to Post // Trigger Registration Form to Post
app.post('/register', async (req, res) => { app.post('/register', async (req, res) => {
@@ -170,7 +179,6 @@ app.post('/register', async (req, res) => {
} }
}); });
/************************ /************************
Home Page Routes Home Page Routes
*************************/ *************************/
@@ -179,10 +187,6 @@ app.get('/home', (req, res) => {
res.render('pages/home'); res.render('pages/home');
}); });
// Import and call generateLeagueRoutes function
const generateLeagueRoutes = require('./resources/routes/league-pages/generate-league-routes');
generateLeagueRoutes(app);
// ***************************************************** // *****************************************************
// <!-- Section 5 : Start Server--> // <!-- Section 5 : Start Server-->
// ***************************************************** // *****************************************************

View File

@@ -1,18 +1,18 @@
const axios = require('axios'); const axios = require('axios');
// Middleware function to fetch leaguees data // Middleware function to fetch leagues data
const fetchleagueesData = async (req, res, next) => { const fetchLeaguesData = async (req, res, next) => {
try { try {
// Array of years to fetch leaguees data // Array of years to fetch leagues data
const league_ids = [2021]; /* Readd , 2002, 2014, 2019, 2015, 2013 */ const league_ids = [2021]; /* Add more league IDs if needed */
// Array to store all leaguees data // Array to store all leagues data
let allLeagues = []; let allLeagues = [];
// Loop through each year and fetch leaguees data // Loop through each year and fetch leagues data
for (const league_id of league_ids) { for (const league_id of league_ids) {
const response = await axios({ const response = await axios({
url: `http://api.football-data.org/v4/competitions/${league_id}/standings?season`, /* Resinsert ${league_id} for 2021 */ url: `http://api.football-data.org/v4/competitions/${league_id}/standings?season`,
method: 'GET', method: 'GET',
headers: { headers: {
'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', // Add your API key here 'X-Auth-Token': '0aa1ed31245d4a36b1ef5a79150324b3', // Add your API key here
@@ -20,34 +20,37 @@ const fetchleagueesData = async (req, res, next) => {
}); });
// Extract relevant data from the API response // Extract relevant data from the API response
const leagues = response.data.leagues.map(league => ({ const league_data = response.data.standings[0].table.map(team => ({
competition: { competition: {
league_id: league.competition.id, league_id: response.data.competition.id,
league_name: league.competition.name, league_name: response.data.competition.name,
league_emblem: league.competition.emblem league_emblem: response.data.competition.emblem
}, },
standings: { standings: {
table: { table: {
league_position: league.standings.table.position, league_position: team.position,
team_id: league.standings.table.team.id, team_id: team.team.id,
team_name: league.standings.table.team.name, team_name: team.team.name,
team_crest: league.standings.table.team.crest team_crest: team.team.crest
}, },
}, },
})); }));
// Concatenate leaguees data to allleaguees array // Concatenate leagues data to allLeagues array
allLeagues = allLeagues.concat(leagues); allLeagues = allLeagues.concat(league_data);
} }
// Attach all leaguees data to res.locals // Attach all leagues data to res.locals
res.locals.leagues = allLeagues; res.locals.leagues = allLeagues;
next(); next();
} catch (error) { }
console.error('Error fetching leaguees data:', error);
catch (error)
{
console.error('Error fetching leagues data:', error);
res.locals.leagues = []; // Set an empty array if there's an error res.locals.leagues = []; // Set an empty array if there's an error
next(); // Call next middleware or route handler next(); // Call next middleware or route handler
} }
}; };
module.exports = fetchleagueesData; module.exports = fetchLeaguesData;

View File

@@ -2,7 +2,7 @@
<!-- Container for all league information (logo, name, country, etc. ) <- top 100px --> <!-- Container for all league information (logo, name, country, etc. ) <- top 100px -->
<div class="container" id="league-information-container"> <div class="container" id="league-information-container">
<img src="{{ leagues.competition.league_emblem }}" alt="League Emblem"> <img src="{{ competition.league_emblem }}" alt="League Emblem">
</div> </div>
<!-- Container to display all stats for league <- bottom rest of the container --> <!-- Container to display all stats for league <- bottom rest of the container -->

View File

@@ -12,7 +12,7 @@
<!-- Homepage Scripts --> <!-- Homepage Scripts -->
<script src="/js/homepage/redirect-to-league-url.js"></script> <script src="/js/homepage/redirect-to-league-url.js"></script>
<script src="/routes/league-pages/generate-league-routes.js"></script>
</footer> </footer>