Skip to content

Commit

Permalink
Fix server configuration for Vercel deployment
Browse files Browse the repository at this point in the history
  • Loading branch information
AryanVBW committed Nov 28, 2024
1 parent 8d94564 commit a674928
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 59 deletions.
138 changes: 81 additions & 57 deletions index.js
Original file line number Diff line number Diff line change
@@ -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:[email protected]/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}`);
});
startServer();
8 changes: 6 additions & 2 deletions vercel.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}

0 comments on commit a674928

Please sign in to comment.