refactor: clean up API_URL definition and improve error handling in authStore

This commit is contained in:
Patryk
2025-06-08 09:21:04 +02:00
parent 0c92a4b4ee
commit 717dd32543
2 changed files with 145 additions and 129 deletions

View File

@@ -2,21 +2,22 @@ import axios from "axios";
import FormData from "form-data"; import FormData from "form-data";
import { useAuthStore } from "@/store/authStore"; import { useAuthStore } from "@/store/authStore";
const API_URL = "https://hopp.zikor.pl/api/v1"; // const API_URL = "https://testowe.zikor.pl/api/v1";
const API_URL = "https://hopp.zikor.pl/api/v1";
export async function listNotices() { export async function listNotices() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
const response = await fetch(`${API_URL}/notices/get/all`, { const response = await fetch(`${API_URL}/notices/get/all`, {
headers: headers headers: headers,
}); });
const data = await response.json(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
throw new Error(response.toString()); throw new Error(response.toString());
} }
return data; return data;
} }
export async function getNoticeById(noticeId) { export async function getNoticeById(noticeId) {
@@ -58,44 +59,40 @@ export async function getImageByNoticeId(noticeId) {
const imageName = listResponse.data[0]; const imageName = listResponse.data[0];
imageUrl = `${API_URL}/images/get/${imageName}`; imageUrl = `${API_URL}/images/get/${imageName}`;
return imageUrl; return imageUrl;
} catch (err) { } catch (err) {
console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`); console.log(`Zdjęcie nie istnieje dla notice o id: ${noticeId}`);
imageUrl = "https://http.cat/404.jpg"; imageUrl = "https://http.cat/404.jpg";
return imageUrl; return imageUrl;
} }
} }
export async function getAllImagesByNoticeId(noticeId) { export async function getAllImagesByNoticeId(noticeId) {
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`); const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`);
if (listResponse.data && listResponse.data.length > 0) { if (listResponse.data && listResponse.data.length > 0) {
return listResponse.data.map(imageName => return listResponse.data.map(
`${API_URL}/images/get/${imageName}` (imageName) => `${API_URL}/images/get/${imageName}`
); );
}
return ["https://http.cat/404.jpg"];
} catch (err) {
if(err.response.status === 404) {
console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
return ["https://http.cat/404.jpg"];
}
console.warn(`Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`, err);
return ["https://http.cat/404.jpg"];
} }
// console.log(`Brak zdjęć dla ogłoszenia o id: ${noticeId}`);
return ["https://http.cat/404.jpg"]; return ["https://http.cat/404.jpg"];
} catch (err) { } catch (err) {
// console.log(`Błąd podczas pobierania listy zdjęć dla ogłoszenia o id: ${noticeId}`, err); if (err.response.status === 404) {
// console.info(`Ogłoszenie o id: ${noticeId} nie posiada zdjęć.`);
return ["https://http.cat/404.jpg"];
}
console.warn(
`Nie udało się pobrać listy zdjęć dla ogłoszenia o id: ${noticeId}`,
err
);
return ["https://http.cat/404.jpg"]; return ["https://http.cat/404.jpg"];
} }
} }
export const uploadImage = async (noticeId, imageUri) => { export const uploadImage = async (noticeId, imageUri) => {
const formData = new FormData(); const formData = new FormData();
const filename = imageUri.split("/").pop(); const filename = imageUri.split("/").pop();

View File

@@ -7,113 +7,132 @@ const API_URL = "https://hopp.zikor.pl/api/v1";
export const useAuthStore = create( export const useAuthStore = create(
persist( persist(
(set) => ({ (set) => {
user_id: null, // Dodaj interceptor tylko raz
token: null, if (!axios.interceptors.response.handlers.length) {
isLoading: false, axios.interceptors.response.use(
error: null, (response) => response,
(error) => {
signIn: async (email, password) => { if (
set({ isLoading: true, error: null }); (error.response && error.response.status === 401) ||
try { error.response.status === 403
const response = await axios.post(`${API_URL}/auth/login`, { ) {
email, set({ user_id: null, token: null, isLoading: false });
password, delete axios.defaults.headers.common["Authorization"];
});
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) {
set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
signUp: async (userData) => {
set({ isLoading: true, error: null });
try {
const response = await axios.post(
`${API_URL}/auth/register`,
userData,
{
headers: { "Content-Type": "application/json" },
} }
); return Promise.reject(error);
}
);
}
const user_id = response.data.user_id; return {
const token = response.data.token; user_id: null,
set({ user_id: user_id, token: token, isLoading: false }); token: null,
isLoading: false,
error: null,
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; signIn: async (email, password) => {
} catch (error) { set({ isLoading: true, error: null });
set({ try {
error: error.response?.data?.message || error.message, const response = await axios.post(`${API_URL}/auth/login`, {
isLoading: false, email,
}); password,
throw error; });
}
},
signInWithGoogle: async (googleToken) => { const user_id = response.data.user_id;
set({ isLoading: true, error: null }); const token = response.data.token;
try { set({ user_id: user_id, token: token, isLoading: false });
const response = await axios.post(
`${API_URL}/auth/google`,
{ googleToken: googleToken },
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
} catch (error) { } catch (error) {
set({ set({
error: error.response?.data?.message || error.message, error: error.response?.data?.message || error.message,
isLoading: false, isLoading: false,
}); });
throw error; throw error;
} }
}, },
signOut: async () => { signUp: async (userData) => {
try { set({ isLoading: true, error: null });
await axios.post(`${API_URL}/auth/logout`); try {
} catch (error) { const response = await axios.post(
console.error("Logout error:", error); `${API_URL}/auth/register`,
} finally { userData,
delete axios.defaults.headers.common["Authorization"]; {
set({ user_id: null, token: null }); headers: { "Content-Type": "application/json" },
} }
}, );
checkAuth: async () => { const user_id = response.data.user_id;
const { token } = useAuthStore.getState(); const token = response.data.token;
if (!token) return null; set({ user_id: user_id, token: token, isLoading: false });
set({ isLoading: true }); axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
try { } catch (error) {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; set({
error: error.response?.data?.message || error.message,
isLoading: false,
});
throw error;
}
},
const response = await axios.get(`${API_URL}/auth/me`); signInWithGoogle: async (googleToken) => {
set({ isLoading: true, error: null });
try {
const response = await axios.post(
`${API_URL}/auth/google`,
{ googleToken: googleToken },
{
headers: { "Content-Type": "application/json" },
}
);
const user_id = response.data.user_id;
const token = response.data.token;
set({ user_id: user_id, token: token, isLoading: false });
set({ user_id: response.data, isLoading: false }); axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
return response.data; } catch (error) {
} catch (error) { set({
delete axios.defaults.headers.common["Authorization"]; error: error.response?.data?.message || error.message,
set({ user_id: null, token: null, isLoading: false }); isLoading: false,
return null; });
} throw error;
}, }
}), },
signOut: async () => {
try {
await axios.post(`${API_URL}/auth/logout`);
} catch (error) {
console.error("Logout error:", error);
} finally {
delete axios.defaults.headers.common["Authorization"];
set({ user_id: null, token: null });
}
},
checkAuth: async () => {
const { token } = useAuthStore.getState();
if (!token) return null;
set({ isLoading: true });
try {
axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
const response = await axios.get(`${API_URL}/auth/me`);
set({ user_id: response.data, isLoading: false });
return response.data;
} catch (error) {
delete axios.defaults.headers.common["Authorization"];
set({ user_id: null, token: null, isLoading: false });
return null;
}
},
};
},
{ {
name: "auth-storage", name: "auth-storage",
storage: createJSONStorage(() => AsyncStorage), storage: createJSONStorage(() => AsyncStorage),