From cbc6acc286a703cc48afa883a7fbbefb148d0bad Mon Sep 17 00:00:00 2001 From: J-onasJones Date: Sun, 18 Aug 2024 05:42:24 +0200 Subject: [PATCH] added analytics tracking --- src/index.js | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 58250e3..a7f8253 100644 --- a/src/index.js +++ b/src/index.js @@ -1,5 +1,5 @@ addEventListener('fetch', (event) => { - event.respondWith(handleRequest(event.request)); + event.respondWith(handleRequest(event)); }); const displayNames = { @@ -14,6 +14,33 @@ const displayNames = { 'jonasjonesstudios-com': 'Jonas_Jones Studios (jonasjonesstudios.com)', }; +async function recordRequest(request) { + + const analyticsData = { + timestamp: Date.now(), + domain: new URL(request.url).hostname, + method: request.method, + path: new URL(request.url).pathname, + ipcountry: request.cf.country, + } + const ANALYTICS_URL = 'https://analytics.jonasjones.dev/requests/record'; + + const response = await fetch(ANALYTICS_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': ANALYTICS_API_KEY, + }, + body: JSON.stringify(analyticsData) + }); + + if (response.ok) { + console.log('Request recorded successfully'); + } else { + console.error('Failed to record request:', response.status, await response.text()); + } +} + function getDisplayName(namespace) { @@ -155,7 +182,9 @@ async function buildsPageConstructor(namespace) { } -async function handleRequest(request) { +async function handleRequest(event) { + const request = event.request; + event.waitUntil(recordRequest(request)); console.log(CLOUDFLARE_ACCOUNT_ID) const { pathname } = new URL(request.url); if (pathname === '/') {