mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-21 20:51:17 -05:00
Add unit preferences to user settings
This commit is contained in:
84
supabase/functions/detect-location/index.ts
Normal file
84
supabase/functions/detect-location/index.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { serve } from "https://deno.land/std@0.168.0/http/server.ts";
|
||||
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
|
||||
};
|
||||
|
||||
interface IPLocationResponse {
|
||||
country: string;
|
||||
countryCode: string;
|
||||
measurementSystem: 'metric' | 'imperial';
|
||||
}
|
||||
|
||||
serve(async (req) => {
|
||||
// Handle CORS preflight requests
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders });
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the client's IP address
|
||||
const forwarded = req.headers.get('x-forwarded-for');
|
||||
const realIP = req.headers.get('x-real-ip');
|
||||
const clientIP = forwarded?.split(',')[0] || realIP || '8.8.8.8'; // fallback to Google DNS for testing
|
||||
|
||||
console.log('Detecting location for IP:', clientIP);
|
||||
|
||||
// Use a free IP geolocation service
|
||||
const geoResponse = await fetch(`http://ip-api.com/json/${clientIP}?fields=status,country,countryCode`);
|
||||
|
||||
if (!geoResponse.ok) {
|
||||
throw new Error('Failed to fetch location data');
|
||||
}
|
||||
|
||||
const geoData = await geoResponse.json();
|
||||
|
||||
if (geoData.status !== 'success') {
|
||||
throw new Error('Invalid location data received');
|
||||
}
|
||||
|
||||
// Countries that primarily use imperial system
|
||||
const imperialCountries = ['US', 'LR', 'MM']; // USA, Liberia, Myanmar
|
||||
const measurementSystem = imperialCountries.includes(geoData.countryCode) ? 'imperial' : 'metric';
|
||||
|
||||
const result: IPLocationResponse = {
|
||||
country: geoData.country,
|
||||
countryCode: geoData.countryCode,
|
||||
measurementSystem
|
||||
};
|
||||
|
||||
console.log('Location detected:', result);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify(result),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error detecting location:', error);
|
||||
|
||||
// Return default (metric) on error
|
||||
const defaultResult: IPLocationResponse = {
|
||||
country: 'Unknown',
|
||||
countryCode: 'XX',
|
||||
measurementSystem: 'metric'
|
||||
};
|
||||
|
||||
return new Response(
|
||||
JSON.stringify(defaultResult),
|
||||
{
|
||||
headers: {
|
||||
...corsHeaders,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
status: 200 // Return 200 even on error to provide fallback
|
||||
}
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user