Additional Features and Advanced Configuration
Setting Authentication Token
Basic Usage
import ApiClient from "hmm-api";
const api = new ApiClient();
// Set authentication token for all future requests
api.setAuthToken("your-jwt-token");
// Clear authentication token
api.setAuthToken(null);
Global Headers Configuration
Adding and Modifying Global Headers
// Set global headers that will be sent with every request
api.setGlobalHeaders({
"X-App-Version": "1.0.0",
"X-Client-Type": "web",
});
// Add additional headers without overwriting existing ones
api.setGlobalHeaders({
"X-Custom-Header": "custom-value",
});
Error Handling Configuration
Custom Error Parsing
const api = new ApiClient({
// Custom error parsing function
parseErrorResponse: (error) => {
// Custom logic to extract error message
if (error.details) {
return error.details.message;
}
return "An unexpected error occurred";
},
});
Toast Notification Configuration
Configuring Toast Notifications
import toast from "your-toast-library";
const api = new ApiClient({
toast: toast,
showGlobalToast: true, // Enable/disable global error toasts
});
Credentials Configuration
Setting Credentials Policy
const api = new ApiClient({
// Credential handling strategies
credentials: "include", // Send cookies cross-origin
// Other options: 'same-origin', 'omit'
});
Complete Initialization Example
import ApiClient from "hmm-api";
import toast from "your-toast-library";
const api = new ApiClient({
// Toast library for notifications
toast: toast,
// Global headers for all requests
globalHeaders: {
"X-App-Version": "1.0.0",
"Accept-Language": "en-US",
},
// Custom error parsing
parseErrorResponse: (error) => {
if (error.code) {
return `Error ${error.code}: ${error.message}`;
}
return "An unexpected error occurred";
},
// Credentials policy
credentials: "include",
// Global toast settings
showGlobalToast: true,
});
// Usage example
async function fetchData() {
// Set authentication token
api.setAuthToken(localStorage.getItem("token"));
// Perform request with all configured settings
const response = await api.get("/data");
}
Environment Considerations
Node.js vs Browser Support
// The ApiClient automatically detects environment
// Toasts are disabled in Node.js environments
const api = new ApiClient({
// These settings work across environments
});
Quick Tips
- Configure global settings during initialization
- Customize error handling and notifications
- Set authentication tokens securely
- Be consistent with global headers
- Understand credential policies