Refactor
This commit is contained in:
@@ -1,46 +1,32 @@
|
||||
/**
|
||||
* Client-side API utilities with authentication handling
|
||||
* Simple client-side fetch function for making API calls with Authorization header.
|
||||
*/
|
||||
|
||||
const getAuthToken = (): string | null => {
|
||||
const token = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1];
|
||||
|
||||
return token || null; // Return null instead of throwing an error
|
||||
};
|
||||
|
||||
export const fetchClient = async <T = unknown>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> => {
|
||||
export async function clientFetch(url: string, options: RequestInit = {}): Promise<any> {
|
||||
try {
|
||||
const authToken = getAuthToken();
|
||||
if (!authToken) {
|
||||
console.warn("No authentication token found. Redirecting to login...");
|
||||
window.location.href = "/login";
|
||||
return Promise.reject("Unauthorized");
|
||||
}
|
||||
const authToken = document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || localStorage.getItem('Authorization');
|
||||
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${endpoint}`, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
...options.headers,
|
||||
},
|
||||
credentials: 'include',
|
||||
});
|
||||
console.log('authToken', authToken);
|
||||
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json();
|
||||
throw new Error(errorData.message || `Request failed: ${res.statusText}`);
|
||||
}
|
||||
// Merge Authorization header if token is found
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(authToken ? { Authorization: `Bearer ${authToken}` } : {}),
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
return res.json();
|
||||
const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL}${url}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
||||
|
||||
return res.json();
|
||||
} catch (error) {
|
||||
console.error(`API request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
console.error(`Client fetch error at ${url}:`, error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,31 +1,13 @@
|
||||
import { fetchClient } from './client-utils';
|
||||
import type { Product, ShippingMethod, ApiResponse } from './types';
|
||||
|
||||
export const ProductService = {
|
||||
getAll: async (): Promise<ApiResponse<Product[]>> =>
|
||||
fetchClient('/products'),
|
||||
|
||||
create: async (product: Omit<Product, '_id'>): Promise<ApiResponse<Product>> =>
|
||||
fetchClient('/products', { method: 'POST', body: JSON.stringify(product) }),
|
||||
|
||||
update: async (id: string, product: Partial<Product>): Promise<ApiResponse<Product>> =>
|
||||
fetchClient(`/products/${id}`, { method: 'PUT', body: JSON.stringify(product) }),
|
||||
|
||||
delete: async (id: string): Promise<ApiResponse<void>> =>
|
||||
fetchClient(`/products/${id}`, { method: 'DELETE' })
|
||||
};
|
||||
|
||||
// Shipping Operations
|
||||
export const ShippingService = {
|
||||
getAll: async (): Promise<ApiResponse<ShippingMethod[]>> =>
|
||||
fetchClient('/shipping-options'),
|
||||
|
||||
create: async (method: Omit<ShippingMethod, '_id'>): Promise<ApiResponse<ShippingMethod>> =>
|
||||
fetchClient('/shipping-options', { method: 'POST', body: JSON.stringify(method) }),
|
||||
|
||||
update: async (id: string, method: Partial<ShippingMethod>): Promise<ApiResponse<ShippingMethod>> =>
|
||||
fetchClient(`/shipping-options/${id}`, { method: 'PUT', body: JSON.stringify(method) }),
|
||||
|
||||
delete: async (id: string): Promise<ApiResponse<void>> =>
|
||||
fetchClient(`/shipping-options/${id}`, { method: 'DELETE' })
|
||||
};
|
||||
/**
|
||||
* Client-side fetch function for API requests.
|
||||
*/
|
||||
export async function fetchData(url: string, options: RequestInit = {}): Promise<any> {
|
||||
try {
|
||||
const res = await fetch(url, options);
|
||||
if (!res.ok) throw new Error(`Request failed: ${res.statusText}`);
|
||||
return res.json();
|
||||
} catch (error) {
|
||||
console.error(`Fetch error at ${url}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
export const fetchData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error("Failed to fetch data");
|
||||
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
|
||||
export const fetchProductData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
return await fetchData(url, {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch product data");
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Error fetching product data:", error);
|
||||
throw error;
|
||||
@@ -21,7 +19,7 @@ export const saveProductData = async (
|
||||
method: "POST" | "PUT" = "POST"
|
||||
) => {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
return await fetchData(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -30,10 +28,6 @@ export const saveProductData = async (
|
||||
credentials: "include",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to save product data");
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Error saving product data:", error);
|
||||
throw error;
|
||||
@@ -42,7 +36,7 @@ export const saveProductData = async (
|
||||
|
||||
export const deleteProductData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
return await fetchData(url, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -50,13 +44,8 @@ export const deleteProductData = async (url: string, authToken: string) => {
|
||||
},
|
||||
credentials: "include",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to delete product data");
|
||||
}
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
console.error("Error deleting product data:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -2,14 +2,14 @@ import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
|
||||
/**
|
||||
* Server-side fetch wrapper with auth handling
|
||||
* Server-side fetch wrapper with authentication.
|
||||
*/
|
||||
export const fetchServer = async <T = unknown>(
|
||||
export async function fetchServer<T = unknown>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> => {
|
||||
): Promise<T> {
|
||||
const cookieStore = cookies();
|
||||
const authToken = await cookieStore.get('Authorization')?.value;
|
||||
const authToken = cookieStore.get('Authorization')?.value;
|
||||
|
||||
if (!authToken) redirect('/login');
|
||||
|
||||
@@ -32,4 +32,4 @@ export const fetchServer = async <T = unknown>(
|
||||
console.error(`Server request to ${endpoint} failed:`, error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
|
||||
export const fetchShippingMethods = async (authToken: string) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
const res = await fetchData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
|
||||
{
|
||||
headers: {
|
||||
@@ -11,8 +13,10 @@ export const fetchShippingMethods = async (authToken: string) => {
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) throw new Error("Failed to fetch shipping options");
|
||||
return await res.json();
|
||||
console.log("Shipping Methods Response:", res);
|
||||
|
||||
if (!res) throw new Error("Failed to fetch shipping options");
|
||||
return res
|
||||
} catch (error) {
|
||||
console.error("Error loading shipping options:", error);
|
||||
throw error;
|
||||
@@ -30,7 +34,7 @@ export const addShippingMethod = async (
|
||||
newShipping: Omit<ShippingMethod, "_id">
|
||||
): Promise<ShippingMethod[]> => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
const res = await fetchData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
|
||||
{
|
||||
method: "POST",
|
||||
@@ -61,7 +65,7 @@ export const addShippingMethod = async (
|
||||
|
||||
export const deleteShippingMethod = async (authToken: string, id: string) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
const res = await fetchData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
@@ -71,7 +75,6 @@ export const deleteShippingMethod = async (authToken: string, id: string) => {
|
||||
);
|
||||
|
||||
if (!res.ok) throw new Error("Failed to delete shipping method");
|
||||
// Since there is no content, just return success status.
|
||||
return { success: res.status === 204 };
|
||||
} catch (error) {
|
||||
console.error("Error deleting shipping method:", error);
|
||||
@@ -85,7 +88,7 @@ export const updateShippingMethod = async (
|
||||
updatedShipping: any
|
||||
) => {
|
||||
try {
|
||||
const res = await fetch(
|
||||
const res = await fetchData(
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
@@ -98,10 +101,10 @@ export const updateShippingMethod = async (
|
||||
}
|
||||
);
|
||||
|
||||
if (!res.ok) throw new Error("Failed to update shipping method");
|
||||
return await res.json();
|
||||
if (!res) throw new Error("Failed to update shipping method");
|
||||
return res
|
||||
} catch (error) {
|
||||
console.error("Error updating shipping method:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
@@ -1,3 +1,5 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
|
||||
export const apiRequest = async <T = any>(endpoint: string, method: string = "GET", body?: T | null) => {
|
||||
try {
|
||||
if (typeof document === "undefined") {
|
||||
@@ -10,7 +12,6 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
?.split("=")[1];
|
||||
|
||||
if (!authToken){
|
||||
// go to /login
|
||||
document.location.href = "/login";
|
||||
throw new Error("No authentication token found");
|
||||
}
|
||||
@@ -32,16 +33,16 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
const API_URL = process.env.NEXT_PUBLIC_API_URL;
|
||||
if (!API_URL) throw new Error("NEXT_PUBLIC_API_URL is not set in environment variables");
|
||||
|
||||
const res = await fetch(`${API_URL}${endpoint}`, options);
|
||||
const res = await fetchData(`${API_URL}${endpoint}`, options);
|
||||
|
||||
if (!res.ok) {
|
||||
if (!res) {
|
||||
const errorResponse = await res.json().catch(() => null);
|
||||
const errorMessage = errorResponse?.error || res.statusText || "Unknown error";
|
||||
throw new Error(`Failed to ${method} ${endpoint}: ${errorMessage}`);
|
||||
}
|
||||
|
||||
// ✅ Return JSON response
|
||||
return await res.json();
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
console.error(`🚨 API Request Error: ${error.message}`);
|
||||
|
||||
Reference in New Issue
Block a user