added some verbose comments

This commit is contained in:
Steve White 2024-10-15 17:04:04 -05:00
parent ea690d14c6
commit ff6b9be749
1 changed files with 39 additions and 6 deletions

View File

@ -65,16 +65,22 @@ export default function Items({ token }) {
/** /**
* This function takes an image name and returns a unique image name. * This function takes an image name and returns a unique image name.
* The purpose of this function is to prevent overwriting of images with the same name.
* If the image name is 'image.jpg', a random string is generated and appended to the image name. * If the image name is 'image.jpg', a random string is generated and appended to the image name.
* This is used to prevent overwriting of images with the same name. * This is used to prevent overwriting of images with the same name.
* For example, if an image named 'image.jpg' is uploaded, the function will return 'image_8xgu6hcu.jpg'
* This ensures that the image will not overwrite any existing image with the same name.
* @param {string} imageName - The name of the image * @param {string} imageName - The name of the image
* @return {string} - The unique image name * @return {string} - The unique image name
*/ */
const generateUniqueImageName = (imageName) => { const generateUniqueImageName = (imageName) => {
if (imageName.toLowerCase() === 'image.jpg') { if (imageName.toLowerCase() === 'image.jpg') {
// Generate a random string
const randomString = Math.random().toString(36).substr(2, 9); const randomString = Math.random().toString(36).substr(2, 9);
// Append the random string to the image name
return `image_${randomString}.jpg`; return `image_${randomString}.jpg`;
} }
// Return the original image name if it's not 'image.jpg'
return imageName; return imageName;
}; };
@ -108,43 +114,70 @@ export default function Items({ token }) {
} }
}; };
/**
* Handle saving a new item.
*
* This function first creates the item without the image, then if the item creation is successful,
* it uploads the image associated with the item.
*
* @return {Promise<void>}
*/
const handleSaveNewItem = async () => { const handleSaveNewItem = async () => {
try { try {
// 1. Create the item first // Step 1: Create the item first
// This sends a request to the API to create a new item with the
// name and description provided. The box_id is set to the selected
// box ID.
const newItemResponse = await axios.post(`${process.env.REACT_APP_API_URL}/items`, { const newItemResponse = await axios.post(`${process.env.REACT_APP_API_URL}/items`, {
name: newItemName, name: newItemName,
description: newItemDescription, description: newItemDescription,
box_id: parseInt(boxId, 10) box_id: parseInt(boxId, 10) // Ensure boxId is converted to an integer
}, { }, {
headers: { headers: {
Authorization: `Bearer ${token}` Authorization: `Bearer ${token}`
} }
}); });
//console.log('New item created:', newItemResponse.status);
// 2. If item creation is successful, upload the image console.log('New item created:', newItemResponse.status);
// Step 2: If item creation is successful, upload the image
if (newItemResponse.status === 200 && fileInputRef.current.files[0]) { if (newItemResponse.status === 200 && fileInputRef.current.files[0]) {
// Get the ID of the newly created item
const newItemId = newItemResponse.data.id; const newItemId = newItemResponse.data.id;
// Get the image file that was uploaded
const imageFile = fileInputRef.current.files[0]; const imageFile = fileInputRef.current.files[0];
// Generate a unique image name by appending a random string
// to the image file name. This is used to prevent overwriting
// of images with the same name.
const newImageName = generateUniqueImageName(imageFile.name); const newImageName = generateUniqueImageName(imageFile.name);
// Upload the image file with the unique name to the server
const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0], newImageName); const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0], newImageName);
if (uploadedImagePath) { if (uploadedImagePath) {
// console.log("Image path to save:", uploadedImagePath); // The image was uploaded successfully. Log the uploaded image path
console.log("Image path to save:", uploadedImagePath);
// You might want to update your item in the backend with the image path // You might want to update your item in the backend with the image path
// For example: // For example:
// await axios.put(...); // await axios.put(...);
} else { } else {
// Handle image upload failure // The image upload failed. Log an error message
console.error('Failed to upload image for the new item.'); console.error('Failed to upload image for the new item.');
} }
} }
// Close the add item dialog
handleCloseAddItemDialog(); handleCloseAddItemDialog();
// Fetch the items again to get the latest data
fetchItems(); fetchItems();
} catch (error) { } catch (error) {
// Catch any errors that may occur during the item creation
// and image upload process. Log the error message
console.error('Error adding item:', error); console.error('Error adding item:', error);
} }
}; };