-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
83 lines (64 loc) · 2.32 KB
/
Copy pathserver.js
File metadata and controls
83 lines (64 loc) · 2.32 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
/* eslint-disable no-undef */
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import { GoogleGenAI } from '@google/genai';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'dist')));
const ai = new GoogleGenAI(process.env.GEMINI_API_KEY);
const triviaCache = new Map();
app.post('/api/trivia', async (req, res) => {
const { location, category } = req.body;
const cacheKey = `${location}:${category}`;
// Prepare cache for this location
if (!triviaCache.has(cacheKey)) {
triviaCache.set(cacheKey, new Set());
}
const usedQuestions = Array.from(triviaCache.get(cacheKey));
try {
console.log('Generating trivia for location:', location, 'category:', category);
const prompt = `
Create one fun, factual multiple-choice trivia question about ${location},
specifically in the category: ${category}.
Do NOT repeat any of the following questions:
${usedQuestions.length > 0 ? usedQuestions.map(q => `- ${q}`).join('\n') : '(none yet)'}
Respond ONLY in JSON with keys:
"question": string,
"choices": array of 4 strings,
"answerIndex": number (0–3).
`;
const result = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: prompt,
});
let text = result.text.trim();
console.log('Raw Gemini output:', text);
text = text.replace(/```json/i, '').replace(/```/g, '').trim();
const jsonStart = text.indexOf('{');
const jsonEnd = text.lastIndexOf('}');
const safeJson = text.slice(jsonStart, jsonEnd + 1);
const parsed = JSON.parse(safeJson);
const newQuestion = parsed.question;
// Store question in cache
triviaCache.get(cacheKey).add(newQuestion);
res.json({
question: parsed.question,
choices: parsed.choices,
answerIndex: parsed.answerIndex
});
} catch (err) {
console.error('Error parsing Gemini output:', err);
res.status(500).json({ error: 'Failed to fetch trivia question.' });
}
});
app.get(/.*/, (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
const PORT = process.env.PORT || 3001;
const HOST = '0.0.0.0';
app.listen(PORT, HOST, () => {
console.log(`Server running on http://${HOST}:${PORT}`);
});