connected api with profile, order

This commit is contained in:
Jelaletdin12
2025-11-15 16:14:01 +05:00
parent 21b9e88c5c
commit f867896817
70 changed files with 2370 additions and 2317 deletions

View File

@@ -1,192 +1,160 @@
import { useMutation, useQuery } from "@tanstack/react-query"
import { apiClient, setAuthToken, clearAuthToken, setGuestToken } from "@/lib/api"
import { queryClient } from "@/lib/queryClient"
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState, useEffect } from "react";
import { apiClient, setAuthToken, clearAuthToken, setGuestToken } from "@/lib/api";
// ==================== TYPES ====================
interface LoginCredentials {
phone_number: string
password?: string
phone_number: string;
password?: string;
}
interface RegisterData {
phone_number: string
name?: string
email?: string
phone_number: string;
name?: string;
email?: string;
}
interface VerifyTokenData {
phone_number: string
code: string
phone_number: string;
code: string;
}
interface AuthResponse {
token?: string
data?: string
user?: any
token?: string;
data?: string;
user?: {
id: string;
phone_number: string;
name?: string;
email?: string;
};
}
/**
* Guest Token alma (RTK mantığı)
*/
// ==================== AUTH STATUS ====================
const getTokenFromCookie = (name: string): string | null => {
if (typeof document === "undefined") return null;
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(";").shift() || null;
return null;
};
export function useAuthStatus() {
const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
const authToken = getTokenFromCookie("authToken");
setIsAuthenticated(!!authToken);
setIsLoading(false);
}, []);
return {
isAuthenticated,
isLoading,
};
}
// ==================== GUEST TOKEN ====================
export function useGetGuestToken() {
return useMutation({
mutationFn: async (): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>("/auth/guest-token", {}, {
headers: {
"Content-Type": "application/json",
},
})
return response.data
const response = await apiClient.post<AuthResponse>("/auth/guest-token", {});
return response.data;
},
onSuccess: (data) => {
const token = data?.token || data?.data
const token = data?.token || data?.data;
if (token) {
setGuestToken(token)
setGuestToken(token);
}
},
onError: (error) => {
console.error("Error fetching guest token:", error)
console.error("Guest token hatası:", error);
},
})
});
}
/**
* Login mutation (RTK mantığı)
*/
// ==================== LOGIN ====================
export function useLogin() {
return useMutation({
mutationFn: async (credentials: LoginCredentials): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>("/auth/login", credentials)
return response.data
},
onSuccess: (data) => {
const token = data?.token || data?.data
if (token) {
setAuthToken(token)
apiClient.setAuthToken(token)
// Tüm cache'i temizle ve yeniden fetch et
queryClient.invalidateQueries()
}
const response = await apiClient.post<AuthResponse>("/auth/login", credentials);
return response.data;
},
onError: (error) => {
console.error("Login error:", error)
console.error("Login hatası:", error);
},
})
});
}
/**
* Register mutation (RTK mantığı)
*/
// ==================== REGISTER ====================
export function useRegister() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (userData: RegisterData): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>("/auth/register", userData)
return response.data
const response = await apiClient.post<AuthResponse>("/auth/register", userData);
return response.data;
},
onSuccess: (data) => {
const token = data?.token || data?.data
const token = data?.token || data?.data;
if (token) {
setAuthToken(token)
apiClient.setAuthToken(token)
// Tüm cache'i temizle
queryClient.invalidateQueries()
setAuthToken(token);
queryClient.invalidateQueries({ queryKey: ["auth-status"] });
}
},
onError: (error) => {
console.error("Register error:", error)
console.error("Register hatası:", error);
},
})
});
}
/**
* Token doğrulama (RTK mantığı)
*/
// ==================== VERIFY TOKEN ====================
export function useVerifyToken() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (verifyData: VerifyTokenData): Promise<AuthResponse> => {
const response = await apiClient.post<AuthResponse>(
"/auth/verify",
verifyData,
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
)
return response.data
const response = await apiClient.post<AuthResponse>("/auth/verify", verifyData);
return response.data;
},
onSuccess: (data) => {
const token = data?.data || data?.token
const token = data?.data || data?.token;
if (token) {
setAuthToken(token)
apiClient.setAuthToken(token)
// Tüm cache'i temizle
queryClient.invalidateQueries()
setAuthToken(token);
queryClient.invalidateQueries({ queryKey: ["auth-status"] });
}
},
onError: (error) => {
console.error("Error verifying token:", error)
console.error("Verify hatası:", error);
},
})
});
}
/**
* Logout işlemi
*/
// ==================== LOGOUT ====================
export function useLogout() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
// Backend'e logout isteği gönder (eğer endpoint varsa)
mutationFn: async (): Promise<void> => {
try {
await apiClient.post("/auth/logout")
await apiClient.post("/auth/logout");
} catch (error) {
// Logout endpoint yoksa da devam et
console.warn("Logout endpoint not available")
console.warn("Logout endpoint çalışmadı:", error);
}
},
onSuccess: () => {
clearAuthToken()
apiClient.clearAuthToken()
// Tüm cache'i temizle
queryClient.clear()
// Login sayfasına yönlendir
clearAuthToken();
queryClient.clear();
if (typeof window !== "undefined") {
window.location.href = "/login"
window.location.href = "/login";
}
},
})
}
/**
* Kullanıcı bilgilerini getir
*/
export function useUser(options?: { enabled?: boolean }) {
return useQuery({
queryKey: ["user", "me"],
queryFn: async () => {
const response = await apiClient.get("/auth/me")
return response.data
onError: (error) => {
console.error("Logout hatası:", error);
clearAuthToken();
queryClient.clear();
},
enabled: options?.enabled !== false,
staleTime: 1000 * 60 * 5, // 5 dakika
retry: false,
})
}
/**
* Authentication durumunu kontrol et
*/
export function useAuthStatus() {
const { data: user, isLoading, error } = useUser({ enabled: true })
return {
isAuthenticated: !!user && !error,
isLoading,
user,
}
});
}