commit c2579d4ee5b939e83b58c93295a622e1e4463589
parent 6eb70f593e1323515cca152b654b638b11373fed
Author: ASWANTH R <aswanthr82@gmail.com>
Date: Sun, 4 Oct 2026 18:42:58 +0530
Refactor count handler for improved readability
Diffstat:
| M | api/count.js | | | 143 | ++++++++++++++++++++++++++++++++++++++++++++++--------------------------------- |
1 file changed, 84 insertions(+), 59 deletions(-)
diff --git a/api/count.js b/api/count.js
@@ -1,71 +1,96 @@
// api/count.js
-export default async function handler(req, res) {
- // Enable CORS
- res.setHeader('Access-Control-Allow-Origin', '*');
+const REPO = 'NodeX-AR/Pytml';
+const PATH = 'count.json';
+const FLUSH_MS = 60_000;
+const FLUSH_THRESHOLD = 25;
- try {
- const token = process.env.GITHUB_TOKEN;
- const repo = 'NodeX-AR/Pytml';
- const path = 'count.json';
+let buffer = { total: 0, origins: {} };
+let cachedTotal = 0;
+let lastFlush = 0;
+let flushing = null;
- // 1. Get the current count from GitHub
- const getRes = await fetch(
- `https://api.github.com/repos/${repo}/contents/${path}`,
- {
- headers: {
- 'Authorization': `token ${token}`,
- 'Accept': 'application/vnd.github.v3+json'
- }
- }
- );
+async function readCount(token) {
+ const r = await fetch(`https://api.github.com/repos/${REPO}/contents/${PATH}`, {
+ headers: { Authorization: `token ${token}`, Accept: 'application/vnd.github.v3+json' }
+ });
+ if (!r.ok) throw new Error('read failed');
+ const data = await r.json();
+ const text = Buffer.from(data.content, 'base64').toString('utf-8');
+ let parsed;
+ try { parsed = JSON.parse(text); }
+ catch { parsed = { total: parseInt(text) || 0, origins: {} }; }
+ return { data: parsed, sha: data.sha };
+}
- if (!getRes.ok) {
- throw new Error('Failed to fetch count');
- }
+async function writeCount(token, payload, sha) {
+ const r = await fetch(`https://api.github.com/repos/${REPO}/contents/${PATH}`, {
+ method: 'PUT',
+ headers: {
+ Authorization: `token ${token}`,
+ Accept: 'application/vnd.github.v3+json',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ message: `Count: ${payload.total}`,
+ content: Buffer.from(JSON.stringify(payload, null, 2)).toString('base64'),
+ sha
+ })
+ });
+ if (!r.ok) throw new Error('write failed');
+}
- const data = await getRes.json();
- const content = Buffer.from(data.content, 'base64').toString('utf-8');
- const currentCount = parseInt(content) || 0;
- const newCount = currentCount + 1;
+function flush() {
+ if (flushing || buffer.total === 0) return flushing;
+ const token = process.env.GITHUB_TOKEN;
+ const snapshot = buffer;
+ buffer = { total: 0, origins: {} };
+ lastFlush = Date.now();
- // 2. Write the new count back to GitHub
- const updateRes = await fetch(
- `https://api.github.com/repos/${repo}/contents/${path}`,
- {
- method: 'PUT',
- headers: {
- 'Authorization': `token ${token}`,
- 'Accept': 'application/vnd.github.v3+json',
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- message: `Count: ${newCount}`,
- content: Buffer.from(String(newCount)).toString('base64'),
- sha: data.sha
- })
+ flushing = (async () => {
+ try {
+ const { data, sha } = await readCount(token);
+ data.total = (data.total || 0) + snapshot.total;
+ data.origins = data.origins || {};
+ for (const [o, n] of Object.entries(snapshot.origins)) {
+ data.origins[o] = (data.origins[o] || 0) + n;
}
- );
-
- if (!updateRes.ok) {
- throw new Error('Failed to update count');
+ data.lastUpdated = new Date().toISOString();
+ await writeCount(token, data, sha);
+ cachedTotal = data.total;
+ } catch (err) {
+ buffer.total += snapshot.total;
+ for (const [o, n] of Object.entries(snapshot.origins)) {
+ buffer.origins[o] = (buffer.origins[o] || 0) + n;
+ }
+ console.error('flush failed:', err);
+ } finally {
+ flushing = null;
}
+ })();
- // 3. Return the count
- res.status(200).json({
- schemaVersion: 1,
- label: "pytml loads",
- message: String(newCount),
- color: "blue"
- });
+ return flushing;
+}
+
+export default async function handler(req, res) {
+ res.setHeader('Access-Control-Allow-Origin', '*');
- } catch (error) {
- console.error('Error:', error);
- // Return a fallback
- res.status(200).json({
- schemaVersion: 1,
- label: "pytml loads",
- message: "error",
- color: "red"
- });
+ let origin = req.headers.origin || '';
+ if (!origin && req.headers.referer) {
+ try { origin = new URL(req.headers.referer).origin; } catch {}
}
+ if (!origin) origin = 'unknown';
+
+ buffer.total += 1;
+ buffer.origins[origin] = (buffer.origins[origin] || 0) + 1;
+
+ if (buffer.total >= FLUSH_THRESHOLD || Date.now() - lastFlush >= FLUSH_MS) {
+ flush().catch(() => {});
+ }
+
+ res.status(200).json({
+ schemaVersion: 1,
+ label: 'pytml loads',
+ message: String(cachedTotal + buffer.total),
+ color: 'blue'
+ });
}