57 lines
1.7 KiB
TypeScript
57 lines
1.7 KiB
TypeScript
import { AuthState } from "@/utils/features/auth/authSlice"
|
|
import { useMutation } from "@tanstack/react-query"
|
|
import { LocationObject } from "expo-location"
|
|
|
|
type ErrorResponse = {
|
|
error: string
|
|
message: string
|
|
statusCode: number
|
|
}
|
|
|
|
type onPostSuccessFunc = (data: any, variables: LocationObject, context: unknown) => void
|
|
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
|
type onErrorFunc = (props: ErrorFuncProps) => void
|
|
|
|
type PostProps = {
|
|
auth: AuthState
|
|
onPostSuccess?: onPostSuccessFunc
|
|
onError?: onErrorFunc
|
|
}
|
|
|
|
export const useGeolocationMutation = ({ auth, onPostSuccess, onError }: PostProps) => {
|
|
return useMutation({
|
|
mutationFn: async (location: LocationObject) => {
|
|
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/`, {
|
|
method: "POST",
|
|
headers: {
|
|
"Authorization": `Bearer ${auth.token}`,
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
longitude: location.coords.longitude,
|
|
latitude: location.coords.latitude,
|
|
speed: location.coords.speed,
|
|
accuracy: location.coords.accuracy,
|
|
altitude: location.coords.altitude,
|
|
altitudeAccuracy: location.coords.altitudeAccuracy,
|
|
timestamp: location.timestamp,
|
|
})
|
|
}).then(resp => resp.json())
|
|
},
|
|
networkMode: 'offlineFirst',
|
|
onSuccess: async (data, location: LocationObject, context: unknown) => {
|
|
if (data.statusCode) {
|
|
if (onError)
|
|
onError({ response: data })
|
|
return
|
|
}
|
|
if (onPostSuccess)
|
|
onPostSuccess(data, location, context)
|
|
},
|
|
onError: async (error: Error) => {
|
|
if (onError)
|
|
onError({ error: error })
|
|
}
|
|
})
|
|
}
|