puffin-app/src/api/aisClient.ts

72 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-05-13 18:50:30 +02:00
import axios from 'axios';
import type { VesselData } from '../types';
// Using MarineTraffic API as an example - you'll need to add your API key
const API_KEY = import.meta.env.VITE_MARINE_TRAFFIC_API_KEY;
const API_BASE_URL = 'https://services.marinetraffic.com/api/vesselmasterdata/v3';
export async function getVesselData(imo: string): Promise<VesselData> {
// For development, return mock data if no API key is present
if (!API_KEY) {
console.warn('No API key found - using mock data');
return getMockVesselData(imo);
}
try {
const response = await axios.get(API_BASE_URL, {
params: {
imo,
apikey: API_KEY,
}
});
if (!response.data || response.data.errors) {
throw new Error('Vessel not found');
}
const data = response.data[0]; // API returns an array
return {
imo: imo,
vesselName: data.VESSEL_NAME || 'Unknown',
type: data.SHIP_TYPE || 'Unknown',
length: Number(data.LENGTH) || 0,
width: Number(data.BREADTH) || 0,
estimatedEnginePower: calculateEstimatedEnginePower(
Number(data.LENGTH),
Number(data.BREADTH),
data.SHIP_TYPE
)
};
} catch (error) {
console.error('AIS API Error:', error);
throw new Error('Failed to fetch vessel data. Please check your IMO number and try again.');
}
}
function calculateEstimatedEnginePower(length: number, width: number, type: string): number {
// Simplified power estimation based on vessel dimensions
const baselinePower = length * width * 5; // kW
// Apply vessel type multiplier
const typeMultiplier = {
'Yacht': 1.2,
'Passenger': 1.5,
'Cargo': 1.0,
'default': 1.0
}[type] || 1.0;
return Math.round(baselinePower * typeMultiplier);
}
// Mock data for development
function getMockVesselData(imo: string): VesselData {
return {
imo: imo,
vesselName: "Sample Yacht",
type: "Yacht",
length: 50,
width: 9,
estimatedEnginePower: 2250 // 50 * 9 * 5
};
}