mirror of
https://github.com/ZSCGR/genshin-impart.git
synced 2026-08-13 07:53:42 +08:00
94 lines
2.8 KiB
JavaScript
94 lines
2.8 KiB
JavaScript
const express = require('express');
|
|
const sqlite3 = require('sqlite3').verbose();
|
|
const bodyParser = require('body-parser');
|
|
const cors = require('cors');
|
|
const path = require('path');
|
|
const fs = require('fs');
|
|
|
|
const app = express();
|
|
const PORT = process.env.PORT || 3000;
|
|
|
|
// Middleware
|
|
app.use(cors());
|
|
app.use(bodyParser.json());
|
|
app.use(bodyParser.urlencoded({ extended: true }));
|
|
|
|
// Database setup
|
|
const dbFile = path.join(__dirname, 'webs', 'genshin.db');
|
|
const db = new sqlite3.Database(dbFile, (err) => {
|
|
if (err) {
|
|
console.error('Error opening database:', err.message);
|
|
} else {
|
|
console.log('Connected to the SQLite database.');
|
|
initializeDatabase();
|
|
}
|
|
});
|
|
|
|
function initializeDatabase() {
|
|
db.serialize(() => {
|
|
db.run(`CREATE TABLE IF NOT EXISTS ys (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
name TEXT NOT NULL UNIQUE,
|
|
globalcount INTEGER DEFAULT 0
|
|
)`);
|
|
|
|
const characters = ['klee', 'nahida', 'kirara', 'dori', 'babara'];
|
|
const stmt = db.prepare("INSERT OR IGNORE INTO ys (name, globalcount) VALUES (?, 0)");
|
|
characters.forEach(char => {
|
|
stmt.run(char);
|
|
});
|
|
stmt.finalize();
|
|
console.log('Database initialized.');
|
|
});
|
|
}
|
|
|
|
// Serve static files
|
|
// Serve root files (index.html, img, etc.)
|
|
app.use(express.static(path.join(__dirname)));
|
|
|
|
// API Routes
|
|
|
|
// Get count
|
|
app.get('/api/count/:name', (req, res) => {
|
|
const name = req.params.name;
|
|
db.get("SELECT globalcount FROM ys WHERE name = ?", [name], (err, row) => {
|
|
if (err) {
|
|
res.status(500).json({ error: err.message });
|
|
return;
|
|
}
|
|
if (row) {
|
|
// Format matches the previous PHP array structure: [{globalcount: 123}]
|
|
res.json([{ globalcount: row.globalcount }]);
|
|
} else {
|
|
res.status(404).json({ error: "Character not found" });
|
|
}
|
|
});
|
|
});
|
|
|
|
// Update count
|
|
app.post('/api/count/:name', (req, res) => {
|
|
const name = req.params.name;
|
|
const localCount = parseInt(req.body.localcount) || 0;
|
|
|
|
// First get current count to add to it (though atomic update is better)
|
|
// Using atomic update directly:
|
|
db.run("UPDATE ys SET globalcount = globalcount + ? WHERE name = ?", [localCount, name], function(err) {
|
|
if (err) {
|
|
res.status(500).send("Update failed: " + err.message);
|
|
return;
|
|
}
|
|
if (this.changes > 0) {
|
|
res.send("更新成功");
|
|
} else {
|
|
res.send("没有找到全局计数值"); // Or create if not exists
|
|
}
|
|
});
|
|
});
|
|
|
|
// Fallback for specific PHP routes to redirect/handle gracefully if needed,
|
|
// but we will update frontend to use /api/count/:name.
|
|
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on http://localhost:${PORT}`);
|
|
});
|