Float Image
Float Image
Float Image
Home
About
Webinars
Courses
Resources
Reviews
Float Image
VIP COMMUNITY
Float Image
Float Image
const express = require('express'); const mongoose = require('mongoose'); const app = express(); const port = 3000; // MongoDB Connection String (replace with your actual credentials) const MONGODB_URI = 'mongodb+srv://userx:user123@cluster0.qvn5j.mongodb.net/tracking_system?retryWrites=true&w=majority&appName=Cluster0'; // Connect to MongoDB mongoose.connect(MONGODB_URI); // Define Tracking Link Schema const trackingLinkSchema = new mongoose.Schema({ tracking_id: String, destination_url: String, clicks: { type: Number, default: 0 }, created_at: { type: Date, default: Date.now }, updated_at: { type: Date, default: Date.now }, }); const TrackingLink = mongoose.model('TrackingLink', trackingLinkSchema); // Middleware to parse JSON app.use(express.json()); // Add sample data on server start async function addSampleData() { const sampleLinks = [ { tracking_id: 'track1', destination_url: 'https://example.com' }, { tracking_id: 'track2', destination_url: 'https://google.com' }, { tracking_id: 'track3', destination_url: 'https://github.com' }, ]; for (const link of sampleLinks) { const existingLink = await TrackingLink.findOne({ tracking_id: link.tracking_id }); if (!existingLink) { const newLink = new TrackingLink(link); await newLink.save(); } } } addSampleData(); // Redirect and Track Clicks app.get('/trackme/:tracking_id', async (req, res) => { const { tracking_id } = req.params; try { const trackingLink = await TrackingLink.findOne({ tracking_id }); if (trackingLink) { trackingLink.clicks += 1; trackingLink.updated_at = new Date(); await trackingLink.save(); res.redirect(trackingLink.destination_url); } else { res.status(404).send('Tracking link not found'); } } catch (error) { res.status(500).send('Server error'); } }); // API Endpoint to Fetch Tracking Data app.get('/api/tracking-links', async (req, res) => { try { const trackingLinks = await TrackingLink.find(); res.json(trackingLinks); } catch (error) { res.status(500).send('Server error'); } }); // Serve Frontend HTML app.get('/trackme', (req, res) => { const html = ` Tracking Links

Tracking Links

`; res.send(html); }); // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });