JavaScript - Fluid Topics

Fluid Topics Integration Guide

Category
Reference Guides
Audience
public
Version
Latest

Create a script.js file and copy the following code block:

const FLUID_TOPICS_PORTAL = "https://sandbox.fluidtopics.net/cge"
const USER_TRAFFIC_API_URL = FLUID_TOPICS_PORTAL + '/analytics/api/v1/traffic/user-activity';

const API_KEY = "eecnQBUJbwKrPAruM4Z9rcPddjsZRR2b"

const API_HEADERS = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + API_KEY,
  'Ft-Calling-App': '{CALLING_APP}'
};

// Fetch Data
async function fetchUserTrafficData() {
  const payload = {
    "startDate": "2024-02-01",
    "endDate": "2025-04-01",
    "groupByPeriod": "month"
  };

  try {
    const response = await fetch(USER_TRAFFIC_API_URL, {
      method: 'POST',
      headers: API_HEADERS,
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching user traffic data:', error);
    throw error;
  }
}

// Rendering
async function renderUserTrafficChart() {
  const tile = document.getElementById('user-traffic');
  const canvas = document.getElementById('user-traffic-chart');
  const loadingIndicator = tile.querySelector('.loading-indicator');

  try {
    const data = await fetchUserTrafficData();
    loadingIndicator.style.display = 'none';

    if (data && data.results && data.results[0] && data.results[0].periods) {
      const periods = data.results[0].periods;
      const labels = periods.map(period => period.periodStartDate.substring(0, 7)); // Get YYYY-MM
      const activeCounts = periods.map(period => period.activeCount);
      const totalCounts = periods.map(period => period.totalCount);

      new Chart(canvas, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
              label: 'Active Users',
              data: activeCounts,
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 2,
              fill: false
            },
            {
              label: 'Total Users',
              data: totalCounts,
              borderColor: 'rgba(255, 99, 132, 1)',
              borderWidth: 2,
              fill: false
            }
          ]
        },
        options: {
          scales: {
            y: {
              beginAtZero: true,
              title: {
                display: true,
                text: 'User Count'
              }
            },
            x: {
              title: {
                display: true,
                text: 'Month'
              }
            }
          }
        }
      });
    } else {
      canvas.outerHTML = '<p>No data available for user traffic.</p>';
    }
  } catch (error) {
    console.error('Error rendering user traffic chart:', error);
    loadingIndicator.textContent = 'Error loading data.';
  }
}

async function renderApiCallsChart() {
  const tile = document.getElementById('api-calls');
  const canvas = document.getElementById('api-calls-chart');
  const loadingIndicator = tile.querySelector('.loading-indicator');

  try {
    const data = await fetchApiCallsData();
    loadingIndicator.style.display = 'none';

    if (data && data.results && Array.isArray(data.results)) {
      const appNames = data.results.map(app => app.name);
      const datasets = data.results.map(app => {
        return {
          label: app.name,
          data: app.periods.map(period => period.callCount),
          backgroundColor: `rgba(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255}, 0.6)`,
          borderWidth: 1
        };
      });

      const periodLabels = data.results[0].periods.map(period => period.periodStartDate.substring(0, 7)); // Get YYYY-MM

      new Chart(canvas, {
        type: 'bar',
        data: {
          labels: periodLabels,
          datasets: datasets
        },
        options: {
          scales: {
            y: {
              beginAtZero: true,
              title: {
                display: true,
                text: 'Call Count'
              }
            },
            x: {
              title: {
                display: true,
                text: 'Month'
              }
            }
          },
          plugins: {
            title: {
              display: true,
              text: 'API Calls by App'
            }
          }
        }
      });
    } else {
      canvas.outerHTML = '<p>No data available for API calls.</p>';
    }
  } catch (error) {
    console.error('Error rendering API calls chart:', error);
    loadingIndicator.textContent = 'Error loading data.';
  }
}

// Call the rendering functions
renderUserTrafficChart();