0% found this document useful (0 votes)
5 views4 pages

API Functions for Product Management

The document contains JavaScript code that defines functions for managing products through a RESTful API using Axios. It includes functions for creating, updating, deleting, and retrieving products, as well as handling authentication and API errors. The code also constructs FormData for product operations, particularly for image uploads.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

API Functions for Product Management

The document contains JavaScript code that defines functions for managing products through a RESTful API using Axios. It includes functions for creating, updating, deleting, and retrieving products, as well as handling authentication and API errors. The code also constructs FormData for product operations, particularly for image uploads.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import axios from 'axios';

const API_BASE_URL = [Link].VITE_BACKEND_API_URL ||


'[Link]

/**
* Gets the authentication token from localStorage
* @returns {string|null} The authentication token or null if not found
*/
const getAuthToken = () => [Link]('qatu_access_token');

/**
* Generates the Authorization header if token exists
* @returns {Object} Headers object with Authorization if token exists
*/
const getAuthHeaders = () => {
const token = getAuthToken();
return token ? { Authorization: `Bearer ${token}` } : {};
};

/**
* Handles API errors and normalizes them
* @param {Error} error - The error object
* @returns {Object} Normalized error object
*/
const handleApiError = (error) => {
if ([Link]) {
const { status, data } = [Link];

switch (status) {
case 400:
return {
type: 'VALIDATION',
message: 'Validation failed',
details: [Link] || [{ field: 'general', msg: [Link] || 'Bad
request' }],
status,
};
case 401:
return {
type: 'AUTH',
message: [Link] || 'Unauthorized access',
status,
};
case 404:
return {
type: 'NOT_FOUND',
message: [Link] || 'Resource not found',
status,
};
default:
return {
type: 'API_ERROR',
message: [Link] || `Server error (status ${status})`,
status,
};
}
} else if ([Link]) {
return {
type: 'NETWORK',
message: 'No response from server',
status: 0,
};
}

return {
type: 'REQUEST',
message: [Link] || 'Unexpected error',
status: 0,
};
};

/**
* Builds FormData for product operations, especially for image upload
* @param {Object} productData
* @returns {FormData}
*/
const buildProductFormData = (productData) => {
const formData = new FormData();

[Link](productData).forEach(([key, value]) => {


if (key !== 'images') {
[Link](key, value);
}
});

if ([Link] && [Link] > 0) {


[Link]([Link]).forEach((file) => {
[Link]('images', file);
});
}

return formData;
};

export const createProduct = async (productData) => {


try {
const formData = buildProductFormData(productData);

const response = await [Link](`${API_BASE_URL}/products`, formData, {


headers: {
...getAuthHeaders(),
'Content-Type': 'multipart/form-data',
},
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

export const updateProduct = async (productId, productData) => {


try {
const formData = buildProductFormData(productData);

const response = await [Link](`${API_BASE_URL}/products/${productId}`,


formData, {
headers: {
...getAuthHeaders(),
'Content-Type': 'multipart/form-data',
},
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

export const deleteProduct = async (productId) => {


try {
const response = await [Link](`${API_BASE_URL}/products/${productId}`, {
headers: getAuthHeaders(),
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

export const getProductById = async (productId) => {


try {
const response = await [Link](`${API_BASE_URL}/products/${productId}`, {
headers: getAuthHeaders(),
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

export const getAllProducts = async (filters = {}) => {


try {
const params = new URLSearchParams();
[Link](filters).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
[Link](key, value);
}
});

const response = await [Link](`${API_BASE_URL}/products?$


{[Link]()}`, {
headers: getAuthHeaders(),
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

export const getSellerProducts = async () => {


try {
const response = await [Link](`${API_BASE_URL}/products?sellerId=current`, {
headers: getAuthHeaders(),
});

return [Link];
} catch (error) {
throw handleApiError(error);
}
};

You might also like