Files
gymflow/services/weight.ts
2025-11-29 12:13:12 +02:00

54 lines
1.5 KiB
TypeScript

import { BodyWeightRecord } from '../types';
const API_URL = '/api';
export const getWeightHistory = async (): Promise<BodyWeightRecord[]> => {
const token = localStorage.getItem('token');
if (!token) return [];
try {
const response = await fetch(`${API_URL}/weight`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Failed to fetch weight history');
}
return await response.json();
} catch (error) {
console.error('Error fetching weight history:', error);
return [];
}
};
export const logWeight = async (weight: number, dateStr?: string): Promise<BodyWeightRecord | null> => {
const token = localStorage.getItem('token');
if (!token) return null;
try {
// Default to today if no date provided
const date = dateStr || new Date().toISOString().split('T')[0];
const response = await fetch(`${API_URL}/weight`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ weight, dateStr: date })
});
if (!response.ok) {
throw new Error('Failed to log weight');
}
return await response.json();
} catch (error) {
console.error('Error logging weight:', error);
return null;
}
};