ADD: Introduce API client and update axios usage across the application

This commit is contained in:
2026-04-27 15:44:07 +02:00
parent a847a8768d
commit 599fb59f24
10 changed files with 102 additions and 74 deletions
+2
View File
@@ -0,0 +1,2 @@
VITE_API_URL=/api/v1
+2
View File
@@ -22,3 +22,5 @@ dist-ssr
*.njsproj *.njsproj
*.sln *.sln
*.sw? *.sw?
.env
+16 -9
View File
@@ -1,16 +1,23 @@
# React + Vite # Listhub Frontend Repository
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. To start developing
Currently, two official plugins are available: ```bash
npm install
```
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) and then
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler ```bash
npm run start
```
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration ## API configuration
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project. The frontend reads the base backend URL from `VITE_API_URL` in `src/config/api.js`.
- Default: `/api/v1` (works with the Vite dev proxy)
- To override it, create a local `.env` file and set `VITE_API_URL` to your backend URL
See `.env.example` for a ready-to-copy example.
+10
View File
@@ -0,0 +1,10 @@
import axios from "axios";
import { API_URL } from "../config/api";
const api = axios.create({
baseURL: API_URL,
});
export { api };
export default api;
+7 -9
View File
@@ -1,10 +1,8 @@
import axios from "axios"; import api from "./api";
export const API_URL = "/api/v1";
export async function login(userData) { export async function login(userData) {
try { try {
const response = await axios.post(`${API_URL}/auth/login`, userData, { const response = await api.post(`/auth/login`, userData, {
headers: {"Content-Type": "application/json"}, headers: {"Content-Type": "application/json"},
}); });
return response.data; return response.data;
@@ -16,7 +14,7 @@ export async function login(userData) {
export async function register(userData) { export async function register(userData) {
try { try {
const response = await axios.post(`${API_URL}/auth/register`, userData, { const response = await api.post(`/auth/register`, userData, {
headers: {"Content-Type": "application/json"}, headers: {"Content-Type": "application/json"},
}); });
return response.data; return response.data;
@@ -28,8 +26,8 @@ export async function register(userData) {
export async function googleLogin(googleToken) { export async function googleLogin(googleToken) {
try { try {
const response = await axios.post( const response = await api.post(
`${API_URL}/auth/google`, `/auth/google`,
{ googleToken: googleToken }, { googleToken: googleToken },
{ {
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
@@ -45,8 +43,8 @@ export async function googleLogin(googleToken) {
export async function logout(token) { export async function logout(token) {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.post( const response = await api.post(
`${API_URL}/auth/logout`, `/auth/logout`,
{}, {},
{ {
headers: headers, headers: headers,
+2 -4
View File
@@ -1,12 +1,10 @@
import axios from "axios";
import { useAuthStore } from "../store/authStore"; import { useAuthStore } from "../store/authStore";
import api from "./api";
const API_URL = "/api/v1";
export async function listCategories() { export async function listCategories() {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
const response = await axios.get(`${API_URL}/vars/categories`, { headers }); const response = await api.get(`/vars/categories`, { headers });
return Array.isArray(response.data) ? response.data : []; return Array.isArray(response.data) ? response.data : [];
} }
+19 -30
View File
@@ -1,18 +1,16 @@
import axios from "axios";
import { useAuthStore } from "../store/authStore"; import { useAuthStore } from "../store/authStore";
import api from "./api";
const API_URL = "/api/v1";
const getAuthHeaders = () => { const getAuthHeaders = () => {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
return token ? { Authorization: `Bearer ${token}` } : {}; return token ? { Authorization: `Bearer ${token}` } : {};
}; };
const buildImageUrl = (imageName) => `${API_URL}/images/get/${imageName}`; const buildImageUrl = (imageName) => `/images/get/${imageName}`;
const fetchImageAsBlobUrl = async (imageUrl) => { const fetchImageAsBlobUrl = async (imageUrl) => {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await axios.get(imageUrl, { const response = await api.get(imageUrl, {
headers, headers,
responseType: "blob", responseType: "blob",
}); });
@@ -22,27 +20,18 @@ const fetchImageAsBlobUrl = async (imageUrl) => {
export async function listNotices() { export async function listNotices() {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await fetch(`${API_URL}/notices/get/all`, { const response = await api.get(`/notices/get/all`, {
headers: headers, headers: headers,
}); });
const data = await response.json(); return response.data;
if (!response.ok) {
throw new Error(data.message || "Failed to fetch notices");
}
return data;
} }
export async function getNoticeById(noticeId) { export async function getNoticeById(noticeId) {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await fetch(`${API_URL}/notices/get/${noticeId}`, { const response = await api.get(`/notices/get/${noticeId}`, {
headers, headers,
}); });
const data = await response.json(); return response.data;
if (!response.ok) {
throw new Error("Error fetching notice");
}
return data;
} }
export async function createNotice(notice) { export async function createNotice(notice) {
@@ -58,7 +47,7 @@ export async function createNotice(notice) {
}; };
try { try {
const response = await axios.post(`${API_URL}/notices/add`, payload, { const response = await api.post(`/notices/add`, payload, {
headers: headers, headers: headers,
}); });
@@ -82,7 +71,7 @@ export async function getImageByNoticeId(noticeId) {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, { const listResponse = await api.get(`/images/list/${noticeId}`, {
headers, headers,
}); });
const imageName = listResponse.data[0]; const imageName = listResponse.data[0];
@@ -98,7 +87,7 @@ export async function getImageByNoticeId(noticeId) {
export async function getAllImagesByNoticeId(noticeId) { export async function getAllImagesByNoticeId(noticeId) {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
try { try {
const listResponse = await axios.get(`${API_URL}/images/list/${noticeId}`, { const listResponse = await api.get(`/images/list/${noticeId}`, {
headers: headers, headers: headers,
}); });
@@ -126,8 +115,8 @@ export const uploadImage = async (noticeId, file, isFirst) => {
formData.append("file", file); formData.append("file", file);
try { try {
const response = await axios.post( const response = await api.post(
`${API_URL}/images/upload/${noticeId}?isMainImage=${isFirst}`, `/images/upload/${noticeId}?isMainImage=${isFirst}`,
formData, formData,
{ headers: headers } { headers: headers }
); );
@@ -140,8 +129,8 @@ export const uploadImage = async (noticeId, file, isFirst) => {
export const deleteNotice = async (noticeId) => { export const deleteNotice = async (noticeId) => {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await axios.delete( const response = await api.delete(
`${API_URL}/notices/delete/${noticeId}`, `/notices/delete/${noticeId}`,
{ headers: headers } { headers: headers }
); );
return response.data; return response.data;
@@ -149,8 +138,8 @@ export const deleteNotice = async (noticeId) => {
export const editNotice = async (noticeId, notice) => { export const editNotice = async (noticeId, notice) => {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await axios.put( const response = await api.put(
`${API_URL}/notices/edit/${noticeId}`, `/notices/edit/${noticeId}`,
{ {
title: notice.title, title: notice.title,
description: notice.description, description: notice.description,
@@ -176,8 +165,8 @@ export const editNotice = async (noticeId, notice) => {
export const deleteImage = async (filename) => { export const deleteImage = async (filename) => {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
const response = await axios.delete( const response = await api.delete(
`${API_URL}/images/delete/${filename}`, `/images/delete/${filename}`,
{ headers: headers } { headers: headers }
); );
return response.data; return response.data;
@@ -187,7 +176,7 @@ export async function listImageNamesByNoticeId(noticeId) {
const headers = getAuthHeaders(); const headers = getAuthHeaders();
try { try {
const response = await axios.get(`${API_URL}/images/list/${noticeId}`, { const response = await api.get(`/images/list/${noticeId}`, {
headers, headers,
}); });
return Array.isArray(response.data) ? response.data : []; return Array.isArray(response.data) ? response.data : [];
+4 -6
View File
@@ -1,15 +1,13 @@
import axios from "axios";
import { useAuthStore } from "../store/authStore"; import { useAuthStore } from "../store/authStore";
import api from "./api";
const API_URL = "/api/v1/wishlist";
export async function toggleNoticeStatus(noticeId) { export async function toggleNoticeStatus(noticeId) {
const { token } = useAuthStore.getState(); const { token } = useAuthStore.getState();
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.post( const response = await api.post(
`${API_URL}/toggle/${noticeId}`, `/wishlist/toggle/${noticeId}`,
{}, {},
{ headers: headers } { headers: headers }
); );
@@ -25,7 +23,7 @@ export async function getWishlist() {
const headers = token ? { Authorization: `Bearer ${token}` } : {}; const headers = token ? { Authorization: `Bearer ${token}` } : {};
try { try {
const response = await axios.get(`${API_URL}/`, { headers: headers }); const response = await api.get(`/wishlist/`, { headers: headers });
return response.data; return response.data;
} catch (error) { } catch (error) {
console.error("Error fetching wishlist:", error); console.error("Error fetching wishlist:", error);
+8
View File
@@ -0,0 +1,8 @@
const DEFAULT_API_URL = "/api/v1";
const trimTrailingSlash = (value) => value.replace(/\/+$/, "");
export const API_URL = trimTrailingSlash(
import.meta.env.VITE_API_URL || DEFAULT_API_URL
);
+26 -10
View File
@@ -1,26 +1,42 @@
import { create } from "zustand"; import { create } from "zustand";
import { persist } from "zustand/middleware"; import { persist } from "zustand/middleware";
import axios from "axios";
import * as api from "../api/auth"; import * as api from "../api/auth";
import apiClient from "../api/api";
export const useAuthStore = create( let authInterceptorId = null;
persist(
(set, get) => { const shouldRedirectToLogin = (error) => {
// Axios interceptor for handling 401/403 const status = Number(error?.response?.status);
axios.interceptors.response.use( return status === 401 || status === 403;
};
const registerAuthInterceptor = (set) => {
if (authInterceptorId !== null) {
return;
}
authInterceptorId = apiClient.interceptors.response.use(
(response) => response, (response) => response,
(error) => { (error) => {
if (error.response && (error.response.status === 401 || error.response.status === 403)) { if (!shouldRedirectToLogin(error)) {
return Promise.reject(error);
}
set({ user_id: null, token: null, isLoading: false }); set({ user_id: null, token: null, isLoading: false });
delete axios.defaults.headers.common["Authorization"]; delete apiClient.defaults.headers.common["Authorization"];
// Redirect to login using window.location for global interceptor
if (window.location.pathname !== '/login') { if (window.location.pathname !== '/login') {
window.location.href = '/login'; window.location.href = '/login';
} }
}
return Promise.reject(error); return Promise.reject(error);
} }
); );
};
export const useAuthStore = create(
persist(
(set, get) => {
registerAuthInterceptor(set);
return { return {
user_id: null, user_id: null,