2024-12-11 22:42:22 +00:00
|
|
|
import { AuthState } from "@/utils/features/auth/authSlice"
|
|
|
|
import { useMutation } from "@tanstack/react-query"
|
|
|
|
|
|
|
|
type ErrorResponse = {
|
|
|
|
error: string
|
|
|
|
message: string
|
|
|
|
statusCode: number
|
|
|
|
}
|
|
|
|
|
|
|
|
type onPostSuccessFunc = () => void
|
|
|
|
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
|
|
|
|
type onErrorFunc = (props: ErrorFuncProps) => void
|
|
|
|
|
|
|
|
type TrainProps = {
|
|
|
|
// addTrain: (payload: TrainPayload) => { payload: GamePayload, type: "train/addTrain" }
|
|
|
|
auth: AuthState
|
|
|
|
onPostSuccess?: onPostSuccessFunc
|
|
|
|
onError?: onErrorFunc
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useAddTrainMutation = ({ auth, onPostSuccess, onError }: TrainProps) => {
|
|
|
|
return useMutation({
|
|
|
|
mutationFn: async (trainId: string) => {
|
|
|
|
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/import/`, {
|
|
|
|
method: "POST",
|
|
|
|
headers: {
|
|
|
|
"Authorization": `Bearer ${auth.token}`,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
body: JSON.stringify({
|
|
|
|
id: trainId,
|
|
|
|
}),
|
|
|
|
}).then(resp => resp.json())
|
|
|
|
},
|
|
|
|
onSuccess: async (data) => {
|
2024-12-12 14:21:58 +00:00
|
|
|
if (data.statusCode) {
|
2024-12-11 22:42:22 +00:00
|
|
|
if (onError)
|
|
|
|
onError({ response: data })
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (onPostSuccess)
|
|
|
|
onPostSuccess()
|
|
|
|
},
|
|
|
|
onError: async (error: Error) => {
|
|
|
|
if (onError)
|
|
|
|
onError({ error: error })
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
2024-12-14 14:57:14 +00:00
|
|
|
|
|
|
|
export const useDeleteTrainMutation = ({ auth, onPostSuccess, onError }: TrainProps) => {
|
|
|
|
return useMutation({
|
|
|
|
mutationFn: async (trainId: string) => {
|
|
|
|
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/trains/${trainId}/`, {
|
|
|
|
method: "DELETE",
|
|
|
|
headers: {
|
|
|
|
"Authorization": `Bearer ${auth.token}`,
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
},
|
|
|
|
})
|
|
|
|
},
|
|
|
|
onSuccess: async (resp) => {
|
|
|
|
if (resp.status >= 400) {
|
|
|
|
if (onError)
|
|
|
|
onError({ response: await resp.json() })
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if (onPostSuccess)
|
|
|
|
onPostSuccess()
|
|
|
|
},
|
|
|
|
onError: async (error: Error) => {
|
|
|
|
if (onError)
|
|
|
|
onError({ error: error })
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|