error-handling #1

Merged
stwhite merged 24 commits from error-handling into main 2024-10-30 15:19:49 +00:00
6 changed files with 253 additions and 327 deletions
Showing only changes of commit 165e4965df - Show all commits

View File

@ -1,8 +1,8 @@
// src/components/Admin.js
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { Link, useNavigate } from 'react-router-dom';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
import './Admin.css'; // Import the CSS file
import {
Typography,
@ -22,7 +22,7 @@ import {
} from '@mui/material';
export default function Admin() {
export default function Admin() {
const [users, setUsers] = useState([]);
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
@ -30,41 +30,26 @@ export default function Admin() {
const navigate = useNavigate();
const fileInputRef = useRef(null);
useEffect(() => {
axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
})
.then(response => {
setUsers(response.data);
})
.catch(error => {
console.error(error);
});
fetchUsers();
}, []);
const fetchUsers = async () => {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
const response = await api.admin.getUsers(localStorage.getItem('token'));
setUsers(response.data);
} catch (error) {
console.error('Error fetching users:', error);
// Optionally, set an error message
// setErrorMessage('Failed to fetch users. Please try again.');
}
};
const handleCreateUser = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/admin/user`, {
const response = await api.admin.createUser(localStorage.getItem('token'), {
username,
password,
email
}, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
setUsers([...users, response.data]);
setUsername('');
@ -77,13 +62,9 @@ export default function Admin() {
const handleDeleteUser = async (id) => {
try {
await axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/admin/user/${id}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
});
await api.admin.deleteUser(localStorage.getItem('token'), id);
setUsers(users.filter(user => user.id !== id));
//setUsers(prevUsers => prevUsers.filter(user => user.id !== id));
fetchUsers();
} catch (error) {
console.error(error);
}
@ -91,10 +72,7 @@ export default function Admin() {
const handleBackupDatabase = async () => {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/admin/db`, {
headers: { Authorization: `Bearer ${localStorage.getItem('token')}` },
responseType: 'blob'
});
const response = await api.admin.backupDb(localStorage.getItem('token'));
const blob = new Blob([response.data], { type: 'application/x-sqlite3' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
@ -112,31 +90,19 @@ export default function Admin() {
const file = fileInputRef.current.files[0];
const formData = new FormData();
formData.append('database', file);
console.log("sending request to restore db")
const token = localStorage.getItem('token');
if (!token) {
throw new Error('No token found in local storage');
}
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/admin/db`, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
});
const response = await api.admin.restoreDb(localStorage.getItem('token'), formData);
if (response.status === 200) {
alert('Database restored successfully');
navigate('/admin');
} else {
throw new Error(`Failed to restore database: ${response.statusText}`);
}
} catch (error) {
console.error(error);
}
};
return (
<Container maxWidth="md">
<Typography variant="h4" gutterBottom>

View File

@ -3,50 +3,43 @@ import React, { useEffect, useState } from 'react';
import { Container, Button, TextField, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
import { Delete as DeleteIcon } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom'; // Import Link from react-router-dom
import axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Boxes({ token }) {
const [boxes, setBoxes] = useState([]);
const [newBoxName, setNewBoxName] = useState('');
const apiUrl = `${process.env.REACT_APP_API_URL}/boxes`;
const debugApi = () => {
if (process.env.DEBUG_API) {
console.log("URL is " + apiUrl);
}
};
debugApi();
useEffect(() => {
//console.log('Token:' + token);
axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, {
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setBoxes(response.data);
});
fetchBoxes();
}, [token]);
// Log boxes state changes outside the useEffect
useEffect(() => {
//console.log('Boxes updated:', boxes);
}, [boxes]);
const handleCreateBox = () => {
axios.post(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, { name: newBoxName }, {
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setBoxes([...boxes, response.data]);
setNewBoxName('');
});
const fetchBoxes = async () => {
try {
const response = await api.boxes.getAll(token);
setBoxes(response.data);
} catch (error) {
console.error('Error fetching boxes:', error);
}
};
const handleDeleteBox = (id) => {
axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/boxes/${id}`, {
headers: { Authorization: `Bearer ${token}` }
}).then(() => {
const handleCreateBox = async () => {
try {
const response = await api.boxes.create(token, { name: newBoxName });
setBoxes([...boxes, response.data]);
setNewBoxName('');
} catch (error) {
console.error('Error creating box:', error);
}
};
const handleDeleteBox = async (id) => {
try {
await api.boxes.delete(token, id);
setBoxes(boxes.filter(box => box.ID !== id));
});
} catch (error) {
console.error('Error deleting box:', error);
}
};
return (

View File

@ -1,33 +1,24 @@
// src/components/ItemDetails.js
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { TextField, Button, Container, Avatar, Tooltip } from '@mui/material';
import axios from 'axios';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
//import { useNavigate } from 'react-router-dom'; // Import useNavigate
import { api } from '../services/api';
export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
const [name, setName] = useState(item.name);
const [description, setDescription] = useState(item.description);
const [imagePath, setImagePath] = useState(item.image_path || '');
const [imageSrc, setImageSrc] = useState('/images/default.jpg'); // Initial default image
const fileInputRef = useRef(null); // Add this line to define fileInputRef
const [imageSrc, setImageSrc] = useState('/images/default.jpg');
const fileInputRef = useRef(null);
const [imageOverlayVisible, setImageOverlayVisible] = useState(false);
// const navigate = useNavigate(); // Initialize useNavigate
// eslint says boxName is defined but never used, but when I remove it it fails to compile
// because boxName is undefined
// eslint-disable-next-line
const [boxName, setBoxName] = useState('');
const [boxes, setBoxes] = useState([]);
const [selectedBoxId, setSelectedBoxId] = useState(item.box_id);
//console.log("item.box_id: " + item.box_id);
useEffect(() => {
const fetchBoxes = async () => {
try {
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes`, {
headers: { Authorization: `Bearer ${token}` }
});
const response = await api.boxes.getAll(token);
setBoxes(response.data);
} catch (error) {
console.error('Error fetching boxes:', error);
@ -36,15 +27,12 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
fetchBoxes();
}, [token]);
const handleBoxChange = (event) => {
const newBoxId = event.target.value;
setSelectedBoxId(newBoxId); // Update only this state
//console.log('Selected box ID:', newBoxId);
setSelectedBoxId(newBoxId);
};
useEffect(() => {
// Fetch box details only when the selectedBoxId changes
const getBoxDetails = async (boxId) => {
try {
const boxIdNumber = +boxId;
@ -52,134 +40,71 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
console.error('Invalid boxId:', boxId);
return;
}
const response = await axios.get(`${process.env.REACT_APP_API_URL}/api/v1/boxes/${boxIdNumber}`, {
headers: { Authorization: `Bearer ${token}` }
});
setBoxName(response.data.name);
const response = await api.boxes.getAll(token);
const box = response.data.find(b => b.ID === boxIdNumber);
if (box) {
setBoxName(box.name);
}
} catch (error) {
console.error('Error fetching box details:', error);
}
};
if (selectedBoxId !== item.box_id) {
getBoxDetails(selectedBoxId); // Fetch when selected box changes
//console.log("selectedBoxId:", selectedBoxId);
getBoxDetails(selectedBoxId);
} else if (item.box_id) {
getBoxDetails(item.box_id); // Fetch when boxId exists and selectedBoxId is empty
//console.log("item.box_id:", item.box_id);
getBoxDetails(item.box_id);
}
}, [selectedBoxId, token, item.box_id]); // Removed `boxId` from dependencies
}, [selectedBoxId, token, item.box_id]);
useEffect(() => {
// Function to fetch image similar to getImageSrc in Items.js
const getImageSrc = (itemId) => {
return axios.get(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}/image`, {
headers: { Authorization: `Bearer ${token}` },
responseType: 'blob'
})
.then(response => {
if (response.status === 200) {
return new Promise((resolve, reject) => {
const fetchItemImage = async () => {
try {
const response = await api.items.getImage(token, item.ID);
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.onload = () => setImageSrc(reader.result);
reader.readAsDataURL(response.data);
});
} else {
throw new Error('Image fetch failed');
} catch (error) {
setImageSrc('/default.jpg');
}
})
.catch(() => {
// Return the data URL of the default image if image fetch fails
return new Promise((resolve, reject) => {
const img = new Image();
img.src = '/default.jpg';
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
const dataURL = canvas.toDataURL();
resolve(dataURL);
};
img.onerror = reject;
});
});
};
// Fetch the image when the component mounts or the item changes
getImageSrc(item.ID).then(dataUrl => setImageSrc(dataUrl));
fetchItemImage();
}, [item.ID, token]);
// const handleCloseItemDetails = () => {
// onClose(); // Call the onClose prop to close the modal
// navigate(`/boxes/${boxId}/items`); // Navigate back to the items list
// };
const handleImageUpload = useCallback(async () => {
if (!fileInputRef.current.files[0]) return;
const formData = new FormData();
formData.append('image', fileInputRef.current.files[0]);
try {
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.ID}/upload`, formData, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
}
});
// Handle successful upload (e.g., show a success message)
//console.log('Image uploaded successfully!', response.data.imagePath);
return response.data.imagePath; // Indicate successful upload
const response = await api.items.uploadImage(token, item.ID, formData);
return response.data.imagePath;
} catch (error) {
// Handle upload error (e.g., show an error message)
console.error('Image upload failed:', error);
}
}, [item.ID, token]);
// eslint-disable-next-line
const updateItemBoxId = async () => {
try {
// eslint-disable-next-line
const response = await axios.put(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.id}`, {
box_id: selectedBoxId,
}, {
headers: { Authorization: `Bearer ${token}` }
});
// Update the item's boxId
item.box_id = selectedBoxId;
} catch (error) {
console.error('Error updating item boxId:', error);
}
};
const handleSave = useCallback( async () => {
const handleSave = useCallback(async () => {
let imagePath;
// 1. Handle image upload first if a new image is selected
if (fileInputRef.current.files[0]) {
// eslint-disable-next-line
imagePath = await handleImageUpload();
}
//console.log("Selected box ID:", selectedBoxId)
// 2. Update item details (name, description, etc.)
try {
await axios.put(`${process.env.REACT_APP_API_URL}/api/v1/items/${item.ID}`, {
await api.items.update(token, item.ID, {
name,
description,
box_id: +selectedBoxId, // Ensure the updated selected box is saved
}, {
headers: { Authorization: `Bearer ${token}` }
box_id: +selectedBoxId,
});
onSave(); // Notify parent to refresh items
onSave();
} catch (error) {
// Handle update error
console.error('Item update failed:', error);
}
}, [item.ID, name, description, selectedBoxId, token, onSave, handleImageUpload]);
const handleImageError = (e) => {
e.target.src = '/images/default.jpg'; // Fallback to default image on error
e.target.src = '/images/default.jpg';
};
const handleAvatarClick = () => {
@ -194,13 +119,12 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
<Container>
<h3>Edit Item: {item.name}</h3>
{/* Display the item image as an avatar */}
<Tooltip title="Click to enlarge">
<Avatar
src={imageSrc}
alt={name}
onError={handleImageError}
sx={{ width: 200, height: 200, marginBottom: '16px' }} // Style the Avatar
sx={{ width: 200, height: 200, marginBottom: '16px' }}
onClick={handleAvatarClick}
/>
</Tooltip>
@ -242,14 +166,11 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
accept="image/*"
ref={fileInputRef}
style={{ display: 'none' }}
id="editItemImageUpload" // Unique ID
id="editItemImageUpload"
/>
<select value={selectedBoxId} onChange={handleBoxChange}>
<option value="">No box</option>
{boxes.map((box) => (
// eslint-disable-next-line
//console.log('Box at the selection point:', box.ID),
//console.log("Box name:", box.name),
<option key={box.ID} value={box.ID}>
{box.name}
</option>
@ -265,7 +186,6 @@ export default function ItemDetails({ item, token, onSave, onClose, boxId }) {
id="image-upload"
style={{ display: 'none' }}
onChange={(e) => {
// You can handle image preview here if needed
setImagePath(e.target.files[0].name);
}}
/>

View File

@ -29,6 +29,7 @@ import axios from 'axios';
import { useParams, useLocation } from 'react-router-dom';
import ItemDetails from './ItemDetails';
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Items({ token }) {
const { id: boxId } = useParams();
@ -131,62 +132,30 @@ export default function Items({ token }) {
*
* @return {Promise<void>}
*/
const handleSaveNewItem = async () => {
try {
// 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}/api/v1/items`, {
const newItemResponse = await api.items.create(token, {
name: newItemName,
description: newItemDescription,
box_id: parseInt(boxId, 10) // Ensure boxId is converted to an integer
}, {
headers: {
Authorization: `Bearer ${token}`
}
box_id: parseInt(boxId, 10)
});
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]) {
// Get the ID of the newly created item
const newItemId = newItemResponse.data.id;
// Get the image file that was uploaded
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 formData = new FormData();
formData.append('image', new File([imageFile], newImageName, {
type: imageFile.type,
}));
// Upload the image file with the unique name to the server
const uploadedImagePath = await handleImageUpload(newItemId, fileInputRef.current.files[0], newImageName);
if (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
// For example:
// await axios.put(...);
} else {
// The image upload failed. Log an error message
console.error('Failed to upload image for the new item.');
}
await api.items.uploadImage(token, newItemId, formData);
}
// Close the add item dialog
handleCloseAddItemDialog();
// Fetch the items again to get the latest data
fetchItems();
} 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);
}
};
@ -252,22 +221,29 @@ export default function Items({ token }) {
}, [token]);
const fetchItems = useCallback(() => {
axios.get( url, {
headers: { Authorization: `Bearer ${token}` }
}).then(response => {
setItems(response.data);
const fetchData = boxId ?
api.items.getByBox(token, boxId) :
api.items.getAll(token);
fetchData
.then(response => {
setItems(response.data);
// Fetch images for each item
response.data.forEach(item => {
getImageSrc(item.ID).then(imageDataUrl => {
setItemImages(prevItemImages => ({
...prevItemImages,
[item.ID]: imageDataUrl
api.items.getImage(token, item.ID)
.then(response => {
const reader = new FileReader();
reader.onload = () => {
setItemImages(prev => ({
...prev,
[item.ID]: reader.result
}));
};
reader.readAsDataURL(response.data);
});
});
});
}, [token, getImageSrc, url]);
}, [token, boxId]);
// lint says I don't need boxId here
useEffect(() => {
@ -302,9 +278,8 @@ export default function Items({ token }) {
// };
const handleDeleteItem = (itemId) => {
axios.delete(`${process.env.REACT_APP_API_URL}/api/v1/items/${itemId}`, {
headers: { Authorization: `Bearer ${token}` }
}).then(() => {
api.items.delete(token, itemId)
.then(() => {
fetchItems();
});
};

View File

@ -1,27 +1,27 @@
// src/components/Login.js
import React, { useState } from 'react';
import { Button, TextField, Container, Typography, Alert } from '@mui/material';
import axios from 'axios';
import { useNavigate } from 'react-router-dom'; // Import useNavigate
import { PRIMARY_COLOR, SECONDARY_COLOR } from '../App';
import { api } from '../services/api';
export default function Login({ setToken }) {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [loginError, setLoginError] = useState(false); // State for login error
const navigate = useNavigate(); // Initialize useNavigate
const [loginError, setLoginError] = useState(false);
const navigate = useNavigate();
const handleLogin = async (e) => {
e.preventDefault();
setLoginError(false); // Reset error state on each login attempt
setLoginError(false);
try {
// eslint-disable-next-line no-template-curly-in-string
const response = await axios.post(`${process.env.REACT_APP_API_URL}/api/v1/login`, { username, password });
const response = await api.login({ username, password });
setToken(response.data.token);
navigate('/boxes');
} catch (error) {
console.error('Login failed', error);
setLoginError(true); // Set error state if login fails
setLoginError(true);
}
};

72
src/services/api.js Normal file
View File

@ -0,0 +1,72 @@
// src/services/api.js
import axios from 'axios';
const createApiClient = () => {
const client = axios.create({
baseURL: process.env.REACT_APP_API_URL
});
const authHeader = (token) => ({ Authorization: `Bearer ${token}` });
return {
// Auth
login: (credentials) =>
client.post('/api/v1/login', credentials),
// Items
items: {
getAll: (token) =>
client.get('/api/v1/items', { headers: authHeader(token) }),
getOne: (token, id) =>
client.get(`/api/v1/items/${id}`, { headers: authHeader(token) }),
create: (token, itemData) =>
client.post('/api/v1/items', itemData, { headers: authHeader(token) }),
update: (token, id, itemData) =>
client.put(`/api/v1/items/${id}`, itemData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/items/${id}`, { headers: authHeader(token) }),
uploadImage: (token, id, formData) =>
client.post(`/api/v1/items/${id}/upload`, formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
getImage: (token, id) =>
client.get(`/api/v1/items/${id}/image`, {
headers: authHeader(token),
responseType: 'blob'
}),
getByBox: (token, boxId) =>
client.get(`/api/v1/boxes/${boxId}/items`, { headers: authHeader(token) }),
},
// Boxes
boxes: {
getAll: (token) =>
client.get('/api/v1/boxes', { headers: authHeader(token) }),
create: (token, boxData) =>
client.post('/api/v1/boxes', boxData, { headers: authHeader(token) }),
delete: (token, id) =>
client.delete(`/api/v1/boxes/${id}`, { headers: authHeader(token) }),
},
// Admin
admin: {
getUsers: (token) =>
client.get('/api/v1/admin/user', { headers: authHeader(token) }),
createUser: (token, userData) =>
client.post('/api/v1/admin/user', userData, { headers: authHeader(token) }),
deleteUser: (token, id) =>
client.delete(`/api/v1/admin/user/${id}`, { headers: authHeader(token) }),
backupDb: (token) =>
client.get('/api/v1/admin/db', {
headers: authHeader(token),
responseType: 'blob'
}),
restoreDb: (token, formData) =>
client.post('/api/v1/admin/db', formData, {
headers: { ...authHeader(token), 'Content-Type': 'multipart/form-data' }
}),
}
};
};
export const api = createApiClient();