-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
152 lines (122 loc) · 3.86 KB
/
Copy pathserver.js
File metadata and controls
152 lines (122 loc) · 3.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
require('dotenv').config();
const express = require('express');
const path = require('path');
const axios = require('axios');
const { connect, getCollection } = require('./models/db');
const userRoutes = require('./routes/user');
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// Connect to MongoDB
connect()
.then(() => console.log(" MongoDB connected"))
.catch(err => console.error(" MongoDB connection failed:", err));
// Mount auth routes
app.use('/api/user', userRoutes);
// In-memory session store
let gameSessions = {};
app.get('/api/start', async (req, res) => {
const amount = parseInt(req.query.amount) || 10;
const category = req.query.category || 9;
try {
const response = await axios.get('https://opentdb.com/api.php', {
params: {
amount,
category,
type: 'multiple',
encode: 'url3986'
}
});
const rawQuestions = response.data.results;
const formattedQuestions = rawQuestions.map(q => {
const choices = [...q.incorrect_answers.map(decodeURIComponent)];
const correctIndex = Math.floor(Math.random() * 4);
choices.splice(correctIndex, 0, decodeURIComponent(q.correct_answer));
return {
question: decodeURIComponent(q.question),
answer: String.fromCharCode(65 + correctIndex),
A: choices[0],
B: choices[1],
C: choices[2],
D: choices[3]
};
});
const gameId = Date.now().toString();
gameSessions[gameId] = {
questions: formattedQuestions,
startTime: Date.now(),
score: 0
};
res.json({ gameId, questions: formattedQuestions });
} catch (err) {
console.error("Trivia API error:", err);
res.status(500).json({ error: "Failed to fetch quiz questions" });
}
});
app.post('/api/submit', async (req, res) => {
const { gameId, userAnswers, username } = req.body;
const session = gameSessions[gameId];
if (!session) {
return res.status(400).json({ error: "Invalid or expired session" });
}
const elapsedTime = (Date.now() - session.startTime) / 1000;
if (elapsedTime > 120) {
delete gameSessions[gameId];
return res.status(403).json({ error: "⏰ Time's up! Quiz expired." });
}
let score = 0;
for (let i = 0; i < session.questions.length; i++) {
if (userAnswers[i] === session.questions[i].answer) {
score++;
}
}
try {
const userScores = getCollection('userScores');
await userScores.insertOne({
username,
score,
timeTaken: elapsedTime,
numQuestions: userAnswers.length,
timestamp: new Date()
});
delete gameSessions[gameId];
res.json({ score, timeTaken: elapsedTime });
} catch (err) {
console.error("Error saving score:", err.message);
res.status(500).json({ error: "Failed to save score to database", detail: err.message });
}
});
app.get('/api/history/:username', async (req, res) => {
const username = req.params.username;
try {
const userScores = getCollection('userScores');
const history = await userScores
.find({ username })
.sort({ timestamp: -1 })
.toArray();
res.json(history);
} catch (err) {
console.error("Error fetching history:", err);
res.status(500).json({ error: "Failed to fetch history" });
}
});
app.get('/api/leaderboard', async (req, res) => {
try {
const userScores = getCollection('userScores');
const topPlayers = await userScores
.find({})
.sort({ score: -1, timeTaken: 1 })
.limit(10)
.toArray();
res.json(topPlayers);
} catch (err) {
console.error("Error fetching leaderboard:", err);
res.status(500).json({ error: "Failed to fetch leaderboard" });
}
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});