Files
fitaiProto/apps/mobile/src/api/attendance.ts
T
dimitar c90f8cb1fa geofence refinement
and manual failsafe
2026-04-03 00:13:22 +02:00

89 lines
2.2 KiB
TypeScript

import { apiClient } from "./client";
import { API_ENDPOINTS } from "../config/api";
import { isAxiosError } from "axios";
export interface Attendance {
id: string;
checkInTime: string;
checkOutTime?: string;
type: string;
notes?: string;
}
export interface AttendanceLocationPayload {
latitude: number;
longitude: number;
accuracy: number;
}
export const attendanceApi = {
getHistory: async (token: string): Promise<Attendance[]> => {
try {
const response = await apiClient.get(API_ENDPOINTS.ATTENDANCE.HISTORY, {
headers: { Authorization: `Bearer ${token}` },
});
return response.data;
} catch (error) {
throw new Error(
getAttendanceErrorMessage(error, "Failed to load attendance history."),
);
}
},
checkIn: async (
type: string,
token: string,
location: AttendanceLocationPayload,
fallbackRequested = false,
): Promise<void> => {
try {
await apiClient.post(
API_ENDPOINTS.ATTENDANCE.CHECK_IN,
{ type, location, fallbackRequested },
{ headers: { Authorization: `Bearer ${token}` } },
);
} catch (error) {
throw new Error(
getAttendanceErrorMessage(error, "Failed to start workout."),
);
}
},
checkOut: async (
token: string,
location: AttendanceLocationPayload,
fallbackRequested = false,
): Promise<void> => {
try {
await apiClient.post(
API_ENDPOINTS.ATTENDANCE.CHECK_OUT,
{ location, fallbackRequested },
{ headers: { Authorization: `Bearer ${token}` } },
);
} catch (error) {
throw new Error(
getAttendanceErrorMessage(error, "Failed to end workout."),
);
}
},
};
function getAttendanceErrorMessage(error: unknown, fallback: string): string {
if (isAxiosError(error)) {
const payload = error.response?.data;
if (typeof payload === "string" && payload.trim()) {
return payload;
}
if (payload && typeof payload === "object") {
const message = (payload as { error?: unknown }).error;
if (typeof message === "string" && message.trim()) {
return message;
}
}
}
return fallback;
}