The categoryService module provides methods to interact with the category endpoints of the Villa Buena E-Commerce API. It handles fetching all available product categories.
The getAll() method can throw errors in the following scenarios:
Network failures
API server errors (5xx)
Invalid endpoints (4xx)
Timeout errors
It’s recommended to wrap service calls in try-catch blocks or use .catch() handlers:
import { categoryService } from './services/categoryService';try { const categories = await categoryService.getAll(); // Handle success} catch (error) { if (error.response) { // The request was made and server responded with error status console.error('Server error:', error.response.status); } else if (error.request) { // The request was made but no response was received console.error('Network error: No response received'); } else { // Something else happened console.error('Error:', error.message); }}
import { categoryService } from './services/categoryService';const categories = await categoryService.getAll();// Render <select> with categories as <option> elements
The Category Service is designed to work seamlessly with the Product Service:
import { categoryService } from './services/categoryService';import { productService } from './services/productService';// Get all categoriesconst categories = await categoryService.getAll();// Fetch products for each categoryconst productsByCategory = {};for (const category of categories) { productsByCategory[category] = await productService.getByCategory(category);}console.log(productsByCategory);
Use the category names returned by categoryService.getAll() as parameters for productService.getByCategory() to ensure consistency.