Separated weight tracking
This commit is contained in:
53
services/weight.ts
Normal file
53
services/weight.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
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;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user