Create server.js
Browse files
server.js
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const express = require("express");
|
2 |
+
const fs = require("fs");
|
3 |
+
require("dotenv").config();
|
4 |
+
|
5 |
+
const app = express();
|
6 |
+
const PORT = 3000;
|
7 |
+
const DATA_FILE = "amounts.json";
|
8 |
+
|
9 |
+
// Middleware to verify API key from query params
|
10 |
+
function authenticate(req, res, next) {
|
11 |
+
const apiKey = req.query.apikey;
|
12 |
+
if (!apiKey || apiKey !== process.env.API_KEY) {
|
13 |
+
return res.status(403).json({ error: "Invalid API key" });
|
14 |
+
}
|
15 |
+
next();
|
16 |
+
}
|
17 |
+
|
18 |
+
// Function to read stored data
|
19 |
+
function readData() {
|
20 |
+
if (!fs.existsSync(DATA_FILE)) return {};
|
21 |
+
return JSON.parse(fs.readFileSync(DATA_FILE));
|
22 |
+
}
|
23 |
+
|
24 |
+
// Function to write stored data
|
25 |
+
function writeData(data) {
|
26 |
+
fs.writeFileSync(DATA_FILE, JSON.stringify(data, null, 2));
|
27 |
+
}
|
28 |
+
|
29 |
+
// /api/amount?chatid=123&amount=50&apikey=yourkey
|
30 |
+
app.get("/api/amount", authenticate, (req, res) => {
|
31 |
+
const { chatid, amount } = req.query;
|
32 |
+
if (!chatid || !amount) return res.status(400).json({ error: "chatid and amount required" });
|
33 |
+
|
34 |
+
const data = readData();
|
35 |
+
if (!data[chatid]) data[chatid] = [];
|
36 |
+
|
37 |
+
const newEntry = { amount: parseFloat(amount), timestamp: new Date().toISOString() };
|
38 |
+
data[chatid].push(newEntry);
|
39 |
+
writeData(data);
|
40 |
+
|
41 |
+
// Call /api/new internally
|
42 |
+
res.redirect(`/api/new?chatid=${chatid}&apikey=${req.query.apikey}`);
|
43 |
+
});
|
44 |
+
|
45 |
+
// /api/new?chatid=123&apikey=yourkey
|
46 |
+
app.get("/api/new", authenticate, (req, res) => {
|
47 |
+
const { chatid } = req.query;
|
48 |
+
if (!chatid) return res.status(400).json({ error: "chatid required" });
|
49 |
+
|
50 |
+
const data = readData();
|
51 |
+
const chatData = data[chatid] || [];
|
52 |
+
|
53 |
+
res.json({
|
54 |
+
chatid,
|
55 |
+
amounts: chatData.map((entry, index) => ({
|
56 |
+
amount: entry.amount,
|
57 |
+
amountId: index + 1,
|
58 |
+
timestamp: entry.timestamp
|
59 |
+
}))
|
60 |
+
});
|
61 |
+
});
|
62 |
+
|
63 |
+
// Start the server
|
64 |
+
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
|