import { NearestEndpointRouter, EndpointManager } from 'edge-utils';
const endpoints = [
{ id: 'us-east', url: 'https://api-us-east.example.com', location: { lat: 39.0438, lng: -77.4874 } },
{ id: 'eu-west', url: 'https://api-eu-west.example.com', location: { lat: 53.3498, lng: -6.2603 } },
{ id: 'asia-pacific', url: 'https://api-asia.example.com', location: { lat: 35.6762, lng: 139.6503 } }
];
const endpointManager = new EndpointManager(endpoints);
const router = new NearestEndpointRouter(endpointManager);
export default {
async fetch(request) {
// Detect user location
const userLocation = await locationDetector.detect(request);
// Find nearest endpoint
const nearestEndpoint = await router.findNearest(userLocation.coordinates);
console.log(`Routing to nearest endpoint: ${nearestEndpoint.id}`);
// Proxy request to nearest endpoint
const response = await fetch(`${nearestEndpoint.url}${new URL(request.url).pathname}`, {
method: request.method,
headers: request.headers,
body: request.body
});
// Add routing information to response
response.headers.set('X-Edge-Location', nearestEndpoint.id);
response.headers.set('X-Response-Time', Date.now() - startTime);
return response;
}
};