Skip to content

Commit

Permalink
strapi integration
Browse files Browse the repository at this point in the history
  • Loading branch information
patra0o committed Apr 20, 2024
1 parent 41d5b06 commit 227b706
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 53 deletions.
107 changes: 56 additions & 51 deletions ad-server.js
Original file line number Diff line number Diff line change
@@ -1,72 +1,77 @@
const cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser'); // parses the https body
const axios = require('axios'); // does a fetch request to geolocation api

const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();

app.use(bodyParser.json());
app.use(cors());
app.options("*", cors());

// Initialize the eventCounter object to store the counts
const STRAPI_BASE_URL = 'http://localhost:1337/api/ad-events'; // Strapi endpoint
const STRAPI_TOKEN = 'dae13e6e613a06ea51e569752f6c7bb35e011d783b7f19ed30e1036d13af10dca0794d9d766e804bad7b58959d6ef84d29227677e1f183b2427ced66d810828902477103e2cb41bcab528ea38b817c7ef07575a25e05719e355da0c444f7309e2bce1ac478b43ada51834796279f6ae730dce9fb62207a1f1c020fc152e81932'; // Strapi API token

const eventCounter = {};

app.post('/ad-event', async (req, res) => {
// we collect eventTypes of click, view and hover
// we also collect device size, time
// adId needs to be made dynamic
const { eventType, location, device, screenSize, timestamp, adId } = req.body;

// Geolocation API endpoint configuration
const url = `http://ip-api.com/json/?fields=status,message,country,regionName,city`;


const { eventType, browser, screenSize, timestamp, adId, device } = req.body;
const geoURL = `http://ip-api.com/json/?fields=status,message,country,regionName,city`;
const stringAdID = adId.toString();
try {
const response = await axios.get(url);
const geoData = response.data;
const geoResponse = await axios.get(geoURL);
const geoData = geoResponse.data;

if (geoData.status !== 'success') {
return res.status(400).json({ message: 'Geolocation data fetch failed', details: geoData.message });
}

// Initialize event count if not existing
if (!eventCounter[adId]) {
eventCounter[adId] = {};
}
if (!eventCounter[adId][eventType]) {
eventCounter[adId][eventType] = 0;
}
eventCounter[adId][eventType] += 1;

if (geoData.status === 'success') {
// Ensure there is an object for the adId
if (!eventCounter[adId]) {
eventCounter[adId] = {};
}
// Ensure there is a counter for the specific eventType
if (!eventCounter[adId][eventType]) {
eventCounter[adId][eventType] = 0;
}
eventCounter[adId][eventType] += 1;
const eventData = {
eventType,
browser,
screenSize,
timestamp,
stringAdID,
country: geoData.country,
region: geoData.regionName,
city: geoData.city,
eventCounts: eventCounter[adId][eventType].toString(),
device, // Convert count to string if necessary
};

// Enhanced log with geolocation data
console.log(JSON.stringify({
message: "Event Received and Processed",
eventType: eventType,
location: location,
device: device,
screenSize: screenSize,
timestamp: timestamp,
country: geoData.country,
region: geoData.regionName,
city: geoData.city,
eventCounts: eventCounter[adId][eventType],
adId: adId
}));
// Post eventData to Strapi
const url = STRAPI_BASE_URL
const data = eventData;
const customHeaders = {
"Content-Type": "application/json",
}

res.json({
message: `Event logged for ${adId} with type ${eventType}`,
location: {
country: geoData.country,
region: geoData.regionName,
city: geoData.city
}
fetch(url, {
method: "POST",
headers: customHeaders,
body: JSON.stringify({ data: data }),
})
.then((response) => response.json())
.then((data) => {
console.log(data);
});
} else {
throw new Error(geoData.message);
}

// Respond with success and the data returned from Strapi
res.json({
message: `Event logged successfully ${eventData}`,
});
console.log(`Event logged successfully ${eventData}`);
} catch (error) {
console.error('Failed to get or process geolocation data:', error);
res.status(500).send('Geolocation api call timeout');
console.error('Failed to process request:', error);
res.status(500).json({ message: 'Internal Server Error', error: error.message });
}
});

Expand Down
5 changes: 3 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -60,14 +60,15 @@ <h1 class="mb-3">Advertisement Tracker</h1>
function collectClientData() {
return {
location: window.location.href,
device: navigator.userAgent,
device: window.navigator.platform,
browser: navigator.userAgent,
screenSize: `${window.innerWidth} x ${window.innerHeight}`,
};
}


// Event handlers
adBanner.addEventListener('mouseover', () => sendDataToAPI('hover', collectClientData()));
// adBanner.addEventListener('mouseover', () => sendDataToAPI('hover', collectClientData()));
adBanner.addEventListener('click', () => sendDataToAPI('click', collectClientData()));

// Visibility tracking for 'view' events
Expand Down

0 comments on commit 227b706

Please sign in to comment.