ugh
This commit is contained in:
@@ -1,76 +0,0 @@
|
||||
/**
|
||||
* API utilities for consistent request handling
|
||||
*/
|
||||
|
||||
/**
|
||||
* Normalizes a URL to ensure it passes through the Next.js API proxy
|
||||
* This ensures all client-side requests go through the Next.js rewrites.
|
||||
*
|
||||
* @param url The endpoint URL to normalize
|
||||
* @returns A normalized URL with proper /api prefix
|
||||
*/
|
||||
export function normalizeApiUrl(url: string): string {
|
||||
if (url.startsWith('/api/')) {
|
||||
return url; // Already has /api/ prefix
|
||||
} else {
|
||||
// Add /api prefix, handling any leading slashes
|
||||
const cleanUrl = url.startsWith('/') ? url : `/${url}`;
|
||||
return `/api${cleanUrl}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a server-side API URL for backend requests
|
||||
* Used in Server Components and API routes to directly access the backend API
|
||||
*
|
||||
* @param endpoint The API endpoint path
|
||||
* @returns A complete URL to the backend API
|
||||
*/
|
||||
export function getServerApiUrl(endpoint: string): string {
|
||||
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
|
||||
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
return apiUrl.endsWith('/')
|
||||
? `${apiUrl}${cleanEndpoint}`
|
||||
: `${apiUrl}/${cleanEndpoint}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the authentication token from cookies or localStorage
|
||||
*/
|
||||
export function getAuthToken(): string | null {
|
||||
if (typeof document === 'undefined') return null; // Guard for SSR
|
||||
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || localStorage.getItem('Authorization');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the user is logged in
|
||||
*/
|
||||
export function isAuthenticated(): boolean {
|
||||
return !!getAuthToken();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates standard API request headers with authentication
|
||||
*
|
||||
* @param token Optional auth token (fetched automatically if not provided)
|
||||
* @param customHeaders Additional headers to include
|
||||
* @returns Headers object ready for fetch requests
|
||||
*/
|
||||
export function createApiHeaders(token?: string | null, customHeaders: Record<string, string> = {}): Headers {
|
||||
const headers = new Headers({
|
||||
'Content-Type': 'application/json',
|
||||
...customHeaders
|
||||
});
|
||||
|
||||
const authToken = token || getAuthToken();
|
||||
if (authToken) {
|
||||
headers.set('Authorization', `Bearer ${authToken}`);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import { toast } from "@/components/ui/use-toast";
|
||||
import { normalizeApiUrl, getAuthToken, createApiHeaders } from "./api-utils";
|
||||
|
||||
type FetchMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
|
||||
|
||||
@@ -12,26 +11,61 @@ interface FetchOptions {
|
||||
headers?: HeadersInit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Client-side fetch utility that ensures all requests go through the Next.js API proxy
|
||||
*/
|
||||
// Helper function to get auth token from cookies
|
||||
function getAuthToken(): string | null {
|
||||
if (typeof document === 'undefined') return null; // Guard for SSR
|
||||
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || null;
|
||||
}
|
||||
|
||||
export async function fetchClient<T>(
|
||||
endpoint: string,
|
||||
options: FetchOptions = {}
|
||||
): Promise<T> {
|
||||
const { method = 'GET', body, headers = {}, ...rest } = options;
|
||||
|
||||
// Normalize the endpoint to ensure it starts with /api/
|
||||
const url = normalizeApiUrl(endpoint);
|
||||
// Get the base API URL from environment or fallback
|
||||
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001';
|
||||
|
||||
// Get auth token and prepare headers
|
||||
const requestHeaders = createApiHeaders(null, headers as Record<string, string>);
|
||||
// Ensure the endpoint starts with a slash
|
||||
const normalizedEndpoint = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
||||
|
||||
// For the specific case of internal-api.inboxi.ng - remove duplicate /api
|
||||
let url;
|
||||
if (apiUrl.includes('internal-api.inboxi.ng')) {
|
||||
// Special case for internal-api.inboxi.ng
|
||||
if (normalizedEndpoint.startsWith('/api/')) {
|
||||
url = `${apiUrl}${normalizedEndpoint.substring(4)}`; // Remove the /api part
|
||||
} else {
|
||||
url = `${apiUrl}${normalizedEndpoint}`;
|
||||
}
|
||||
} else {
|
||||
// Normal case for other environments
|
||||
url = `${apiUrl}${normalizedEndpoint}`;
|
||||
}
|
||||
|
||||
// Get auth token from cookies
|
||||
const authToken = getAuthToken();
|
||||
|
||||
// Prepare headers with authentication if token exists
|
||||
const requestHeaders: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...(headers as Record<string, string>),
|
||||
};
|
||||
|
||||
if (authToken) {
|
||||
// Backend expects "Bearer TOKEN" format
|
||||
requestHeaders['Authorization'] = `Bearer ${authToken}`;
|
||||
console.log('Authorization header set to:', `Bearer ${authToken.substring(0, 10)}...`);
|
||||
}
|
||||
|
||||
// Log request details (useful for debugging)
|
||||
console.log('API Request:', {
|
||||
url,
|
||||
method,
|
||||
hasAuthToken: requestHeaders.has('Authorization')
|
||||
hasAuthToken: !!authToken
|
||||
});
|
||||
|
||||
const fetchOptions: RequestInit = {
|
||||
@@ -50,22 +84,24 @@ export async function fetchClient<T>(
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorMessage = errorData.message || errorData.error || `Request failed with status ${response.status}`;
|
||||
const errorMessage = errorData.message || errorData.error || 'An error occurred';
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Handle 204 No Content responses
|
||||
if (response.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
const data = await response.json();
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('API request failed:', error);
|
||||
|
||||
// Only show toast in browser environment
|
||||
// Only show toast if this is a client-side error (not during SSR)
|
||||
if (typeof window !== 'undefined') {
|
||||
const message = error instanceof Error ? error.message : 'Failed to connect to server';
|
||||
|
||||
toast({
|
||||
title: 'Error',
|
||||
description: message,
|
||||
|
||||
@@ -1,4 +1,47 @@
|
||||
import { normalizeApiUrl, getAuthToken, createApiHeaders } from './api-utils';
|
||||
/**
|
||||
* Normalizes a URL to ensure it has the correct /api prefix
|
||||
* This prevents double prefixing which causes API errors
|
||||
*/
|
||||
function normalizeApiUrl(url: string): string {
|
||||
// Remove any existing /api or api prefix
|
||||
const cleanPath = url.replace(/^\/?(api\/)+/, '');
|
||||
|
||||
// Add a single /api prefix
|
||||
return `/api/${cleanPath.replace(/^\//, '')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the authentication token from cookies or localStorage
|
||||
*/
|
||||
function getAuthToken(): string | null {
|
||||
if (typeof document === 'undefined') return null; // Guard for SSR
|
||||
|
||||
return document.cookie
|
||||
.split('; ')
|
||||
.find(row => row.startsWith('Authorization='))
|
||||
?.split('=')[1] || localStorage.getItem('Authorization');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates standard API request headers with authentication
|
||||
*
|
||||
* @param token Optional auth token (fetched automatically if not provided)
|
||||
* @param customHeaders Additional headers to include
|
||||
* @returns Headers object ready for fetch requests
|
||||
*/
|
||||
function createApiHeaders(token?: string | null, customHeaders: Record<string, string> = {}): Headers {
|
||||
const headers = new Headers({
|
||||
'Content-Type': 'application/json',
|
||||
...customHeaders
|
||||
});
|
||||
|
||||
const authToken = token || getAuthToken();
|
||||
if (authToken) {
|
||||
headers.set('Authorization', `Bearer ${authToken}`);
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple client-side fetch function for making API calls with Authorization header.
|
||||
@@ -12,6 +55,8 @@ export async function clientFetch<T = any>(url: string, options: RequestInit = {
|
||||
// Normalize URL to ensure it uses the Next.js API proxy
|
||||
const fullUrl = normalizeApiUrl(url);
|
||||
|
||||
console.log(`Fetching URL: ${fullUrl}`);
|
||||
|
||||
const res = await fetch(fullUrl, {
|
||||
...options,
|
||||
headers,
|
||||
|
||||
@@ -1,27 +1,13 @@
|
||||
/**
|
||||
* Client-side fetch function for API requests.
|
||||
* A simple wrapper over fetch with improved error handling.
|
||||
*/
|
||||
export async function fetchData<T = any>(url: string, options: RequestInit = {}): Promise<T> {
|
||||
export async function fetchData(url: string, options: RequestInit = {}): Promise<any> {
|
||||
try {
|
||||
const res = await fetch(url, options);
|
||||
|
||||
// Check for no content response
|
||||
if (res.status === 204) {
|
||||
return {} as T;
|
||||
}
|
||||
|
||||
// Handle errors
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({}));
|
||||
const errorMessage = errorData.message || errorData.error || `Request failed: ${res.status} ${res.statusText}`;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Parse normal response
|
||||
return await res.json();
|
||||
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;
|
||||
console.error(`Fetch error at ${url}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
import { normalizeApiUrl } from './api-utils';
|
||||
|
||||
/**
|
||||
* Fetches product data from the API
|
||||
*/
|
||||
export const fetchProductData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
return await fetchData(normalizeApiUrl(url), {
|
||||
return await fetchData(url, {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
credentials: "include",
|
||||
});
|
||||
@@ -16,9 +12,6 @@ export const fetchProductData = async (url: string, authToken: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves product data to the API
|
||||
*/
|
||||
export const saveProductData = async (
|
||||
url: string,
|
||||
data: any,
|
||||
@@ -26,7 +19,7 @@ export const saveProductData = async (
|
||||
method: "POST" | "PUT" = "POST"
|
||||
) => {
|
||||
try {
|
||||
return await fetchData(normalizeApiUrl(url), {
|
||||
return await fetchData(url, {
|
||||
method,
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -41,15 +34,12 @@ export const saveProductData = async (
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Uploads a product image
|
||||
*/
|
||||
export const saveProductImage = async(url: string, file: File, authToken: string) => {
|
||||
export const saveProductImage = async(url: string, file:File, authToken: string) => {
|
||||
try{
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
|
||||
return await fetchData(normalizeApiUrl(url), {
|
||||
return await fetchData(url, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -62,12 +52,9 @@ export const saveProductImage = async(url: string, file: File, authToken: string
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a product
|
||||
*/
|
||||
export const deleteProductData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
return await fetchData(normalizeApiUrl(url), {
|
||||
return await fetchData(url, {
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -81,12 +68,10 @@ export const deleteProductData = async (url: string, authToken: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Fetches product stock information
|
||||
*/
|
||||
// Stock management functions
|
||||
export const fetchStockData = async (url: string, authToken: string) => {
|
||||
try {
|
||||
return await fetchData(normalizeApiUrl(url), {
|
||||
return await fetchData(url, {
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
credentials: "include",
|
||||
});
|
||||
@@ -96,9 +81,6 @@ export const fetchStockData = async (url: string, authToken: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates product stock information
|
||||
*/
|
||||
export const updateProductStock = async (
|
||||
productId: string,
|
||||
stockData: {
|
||||
@@ -109,7 +91,7 @@ export const updateProductStock = async (
|
||||
authToken: string
|
||||
) => {
|
||||
try {
|
||||
const url = `/api/stock/${productId}`;
|
||||
const url = `${process.env.NEXT_PUBLIC_API_URL}/stock/${productId}`;
|
||||
return await fetchData(url, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
|
||||
@@ -1,6 +1,21 @@
|
||||
import { cookies } from 'next/headers';
|
||||
import { redirect } from 'next/navigation';
|
||||
import { getServerApiUrl } from './api-utils';
|
||||
|
||||
/**
|
||||
* Constructs a server-side API URL for backend requests
|
||||
* Used in Server Components and API routes to directly access the backend API
|
||||
*
|
||||
* @param endpoint The API endpoint path
|
||||
* @returns A complete URL to the backend API
|
||||
*/
|
||||
function getServerApiUrl(endpoint: string): string {
|
||||
const apiUrl = process.env.SERVER_API_URL || 'https://internal-api.inboxi.ng/api';
|
||||
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.substring(1) : endpoint;
|
||||
|
||||
return apiUrl.endsWith('/')
|
||||
? `${apiUrl}${cleanEndpoint}`
|
||||
: `${apiUrl}/${cleanEndpoint}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side fetch wrapper with authentication.
|
||||
|
||||
@@ -1,22 +1,9 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
import { normalizeApiUrl } from './api-utils';
|
||||
|
||||
/**
|
||||
* Interface for shipping method data
|
||||
*/
|
||||
interface ShippingMethod {
|
||||
name: string;
|
||||
price: number;
|
||||
_id?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches all shipping methods for the current store
|
||||
*/
|
||||
export const fetchShippingMethods = async (authToken: string) => {
|
||||
try {
|
||||
const res = await fetchData(
|
||||
`/api/shipping-options`,
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${authToken}`,
|
||||
@@ -36,16 +23,19 @@ export const fetchShippingMethods = async (authToken: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds a new shipping method
|
||||
*/
|
||||
interface ShippingMethod {
|
||||
name: string;
|
||||
price: number;
|
||||
_id?: string;
|
||||
}
|
||||
|
||||
export const addShippingMethod = async (
|
||||
authToken: string,
|
||||
newShipping: Omit<ShippingMethod, "_id">
|
||||
): Promise<ShippingMethod[]> => {
|
||||
try {
|
||||
const res = await fetchData(
|
||||
`/api/shipping-options`,
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
@@ -79,13 +69,10 @@ export const addShippingMethod = async (
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes a shipping method by ID
|
||||
*/
|
||||
export const deleteShippingMethod = async (authToken: string, id: string) => {
|
||||
try {
|
||||
const res = await fetchData(
|
||||
`/api/shipping-options/${id}`,
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: { Authorization: `Bearer ${authToken}` },
|
||||
@@ -101,17 +88,14 @@ export const deleteShippingMethod = async (authToken: string, id: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates an existing shipping method
|
||||
*/
|
||||
export const updateShippingMethod = async (
|
||||
authToken: string,
|
||||
id: string,
|
||||
updatedShipping: Partial<ShippingMethod>
|
||||
updatedShipping: any
|
||||
) => {
|
||||
try {
|
||||
const res = await fetchData(
|
||||
`/api/shipping-options/${id}`,
|
||||
`${process.env.NEXT_PUBLIC_API_URL}/shipping-options/${id}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
|
||||
@@ -1,17 +1,11 @@
|
||||
import { fetchData } from '@/lib/data-service';
|
||||
import { normalizeApiUrl } from './api-utils';
|
||||
|
||||
/**
|
||||
* Sends authenticated API requests, ensuring they go through the Next.js API proxy
|
||||
*/
|
||||
export const apiRequest = async <T = any>(endpoint: string, method: string = "GET", body?: T | null) => {
|
||||
try {
|
||||
// Enforce client-side execution
|
||||
if (typeof document === "undefined") {
|
||||
throw new Error("API requests must be made from the client side.");
|
||||
}
|
||||
|
||||
// Get authentication token
|
||||
const authToken = document.cookie
|
||||
.split("; ")
|
||||
.find((row) => row.startsWith("Authorization="))
|
||||
@@ -22,7 +16,6 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
throw new Error("No authentication token found");
|
||||
}
|
||||
|
||||
// Prepare request options
|
||||
const options: RequestInit = {
|
||||
method,
|
||||
headers: {
|
||||
@@ -36,10 +29,10 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
options.body = JSON.stringify(body);
|
||||
}
|
||||
|
||||
// Normalize URL to ensure it uses the Next.js API proxy
|
||||
const url = normalizeApiUrl(endpoint);
|
||||
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 fetchData(url, options);
|
||||
const res = await fetchData(`${API_URL}${endpoint}`, options);
|
||||
|
||||
if (!res) {
|
||||
const errorResponse = await res.json().catch(() => null);
|
||||
@@ -50,11 +43,11 @@ export const apiRequest = async <T = any>(endpoint: string, method: string = "GE
|
||||
return res;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
console.error(`API Request Error: ${error.message}`);
|
||||
console.error(`🚨 API Request Error: ${error.message}`);
|
||||
throw new Error(error.message);
|
||||
}
|
||||
|
||||
console.error("An unknown error occurred", error);
|
||||
console.error("❌ An unknown error occurred", error);
|
||||
throw new Error("An unknown error occurred");
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user