static2api/frontend/script.js

88 lines
No EOL
3.3 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
// Set the base URL for the API
// When running locally without the container, you would use:
const API_BASE_URL = 'http://localhost:8000';
// When accessing the API running in a container, you would use:
// const API_BASE_URL = 'http://localhost:8000';
// Adjust the port if needed according to your container setup
// Function to fetch data from the API and update the UI
async function fetchEndpoint(endpoint, elementId) {
const dataElement = document.getElementById(elementId);
try {
const response = await fetch(`${API_BASE_URL}${endpoint}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Create a formatted JSON string with syntax highlighting
const formattedJson = JSON.stringify(data, null, 2);
// Update the UI with the fetched data
dataElement.innerHTML = `<pre>${formattedJson}</pre>`;
return data; // Return the data for potential further processing
} catch (error) {
dataElement.innerHTML = `<div class="error">Error: ${error.message}</div>`;
console.error(`Failed to fetch ${endpoint}:`, error);
return null;
}
}
// Fetch data from all endpoints
fetchEndpoint('/', 'root-data');
fetchEndpoint('/api/users', 'users-data');
// Fetch contacts data and then process it to display locations
fetchEndpoint('/api/contacts', 'contacts-data')
.then(contactsData => {
if (contactsData) {
// Process the contacts data to extract unique locations
displayLocationsExample(contactsData);
}
});
// Function to display the locations example
function displayLocationsExample(contactsData) {
const locationsElement = document.getElementById('locations-example');
try {
// Extract all unique locations from the contacts data
const locations = [...new Set(contactsData.map(contact => contact.location))];
if (locations.length === 0) {
locationsElement.innerHTML = '<p>No locations found in the contacts data.</p>';
return;
}
// Create HTML for the locations list
const locationsHTML = `
<p>Found ${locations.length} unique location(s):</p>
<ul class="location-list">
${locations.map(location => `
<li class="location-item">${location}</li>
`).join('')}
</ul>
<p>Code example:</p>
<pre>
// JavaScript to extract unique locations
const locations = [...new Set(
contactsData.map(contact => contact.location)
)];
console.log(locations); // ${JSON.stringify(locations)}
</pre>
`;
locationsElement.innerHTML = locationsHTML;
} catch (error) {
locationsElement.innerHTML = `<div class="error">Error processing locations: ${error.message}</div>`;
console.error('Error processing locations:', error);
}
}
});