From a674928b43ab36d304036956f89b1b5e1967ffbd Mon Sep 17 00:00:00 2001 From: AryanVBW Date: Thu, 28 Nov 2024 22:39:25 +0530 Subject: [PATCH] Fix server configuration for Vercel deployment --- index.js | 138 ++++++++++++++++++++++++++++++---------------------- vercel.json | 8 ++- 2 files changed, 87 insertions(+), 59 deletions(-) diff --git a/index.js b/index.js index 5ad6926..1dfd671 100644 --- a/index.js +++ b/index.js @@ -1,74 +1,98 @@ -const express = require('express') +const express = require('express'); const mongoose = require("mongoose"); -const moment = require('moment'); // require +const moment = require('moment'); +const path = require('path'); moment().format(); -const app = express() -const port = process.env.PORT || 3000 +const app = express(); +const port = process.env.PORT || 3000; -app.set('view engine' , 'ejs') -app.use(express.static("public")) +// Middleware +app.set('view engine', 'ejs'); +app.use(express.static(path.join(__dirname, 'public'))); app.use(express.json()); const mongoURI = process.env.MONGODB_URI || "mongodb+srv://kanishkranjan17:kJjPjGDTqnlWZWEi@leaderboard.5gmx8.mongodb.net/leaderboard"; -const databaseName = "leaderboard"; - - -mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) - .then(() => { +// Connect to MongoDB +const connectDB = async () => { + try { + await mongoose.connect(mongoURI, { + useNewUrlParser: true, + useUnifiedTopology: true + }); console.log("Connected to MongoDB!"); - console.log(moment.locale()); - - const User = mongoose.model("User", new mongoose.Schema({}, { strict: false }), "CSES"); + } catch (error) { + console.error("MongoDB connection error:", error); + process.exit(1); + } +}; - app.get("/", async (req, res) => { - try { - const users = await User.find(); - console.log(users); - let usersData = [] ; - for(let userData of users){ - timeline = [false , false , false , false , false , false , false]; - const noOfDaysInWeek = 7 - for (let index = 0; index < noOfDaysInWeek; index++) { - const reqDate = moment("2024-12-08", "YYYY-MM-DD").subtract(index, 'days').format('DD/MM/YYYY'); - const prevDate = moment("2024-12-08", "YYYY-MM-DD").subtract(index+1, 'days').format('DD/MM/YYYY'); - console.log(reqDate + " " + prevDate ); +// Define User model +const User = mongoose.model("User", new mongoose.Schema({ + username: String, + solved: Object, + streak: Number, + questionSolved: Number +}, { strict: false }), "CSES"); - - if(reqDate in userData['solved'] && prevDate in userData['solved']){ - timeline[noOfDaysInWeek - index -1] = (parseInt(userData['solved'][reqDate]) > parseInt(userData['solved'][prevDate])) ; - console.log(timeline[index]); - console.log((parseInt(userData['solved'][reqDate])+" > "+parseInt(userData['solved'][prevDate]))); - - } - } - usersData.push({name : userData.username , timeline : timeline , streak : userData.streak , questionSolved : userData.questionSolved}); - } - res.render("index", { data : usersData }); - } catch (error) { - console.error("Error fetching data:", error); - res.status(500).send("Error fetching data"); +// Routes +app.get("/", async (req, res) => { + try { + const users = await User.find(); + const usersData = users.map(userData => { + const timeline = Array(7).fill(false); + const noOfDaysInWeek = 7; + + for (let index = 0; index < noOfDaysInWeek; index++) { + const reqDate = moment("2024-12-08", "YYYY-MM-DD") + .subtract(index, 'days') + .format('DD/MM/YYYY'); + const prevDate = moment("2024-12-08", "YYYY-MM-DD") + .subtract(index + 1, 'days') + .format('DD/MM/YYYY'); + + if (userData.solved && + userData.solved[reqDate] !== undefined && + userData.solved[prevDate] !== undefined) { + timeline[noOfDaysInWeek - index - 1] = + parseInt(userData.solved[reqDate]) > parseInt(userData.solved[prevDate]); + } } + + return { + name: userData.username, + timeline: timeline, + streak: userData.streak || 0, + questionSolved: userData.questionSolved || 0 + }; }); + + res.render("index", { data: usersData }); + } catch (error) { + console.error("Error fetching data:", error); + res.status(500).json({ error: "Error fetching data", details: error.message }); + } +}); - }) - .catch((err) => console.error("Error connecting to MongoDB:", err)); +// Error handling middleware +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).json({ error: "Something broke!", details: err.message }); +}); -// app.get('/', (req, res) => { -// // res.send('Hello World!') -// res.render('index' , {data : [ -// {name:"Kanishk" , timeline : [1,1,0,0,1,0] , streak : 1}, -// {name:"Neel" , timeline : [1,0,0,1,1,0] , streak : 4}, -// {name:"Ritwik" , timeline : [1,0,0,0,1,1] , streak : 3}, -// {name:"Priyanshu" , timeline : [1,0,1,0,1,0] , streak : 1}, -// {name:"Vivek" , timeline : [1,1,1,1,1,1] , streak : 10}, - - -// ]}) -// }) +// Start server +const startServer = async () => { + try { + await connectDB(); + app.listen(port, () => { + console.log(`Server running on http://localhost:${port}`); + }); + } catch (error) { + console.error("Server startup error:", error); + process.exit(1); + } +}; -app.listen(port, () => { - console.log(`Server running on http://localhost:${port}`); -}); \ No newline at end of file +startServer(); \ No newline at end of file diff --git a/vercel.json b/vercel.json index df47e78..003078a 100644 --- a/vercel.json +++ b/vercel.json @@ -2,14 +2,18 @@ "version": 2, "builds": [ { - "src": "./index.js", + "src": "index.js", "use": "@vercel/node" } ], "routes": [ + { + "src": "/public/(.*)", + "dest": "/public/$1" + }, { "src": "/(.*)", - "dest": "/" + "dest": "/index.js" } ] }