System Utilities
System utilities in this project provide essential services for infrastructure monitoring, backend configuration testing, and common frontend UI patterns. These are primarily implemented through the UtilsService client and a set of specialized React hooks.
Monitor Backend Health
You can verify the status of the backend API using the UtilsService.healthCheck method. This is used by the infrastructure to ensure the service is responsive.
import { UtilsService } from "@/client"
const checkHealth = async () => {
try {
const isHealthy = await UtilsService.healthCheck()
console.log("System Status:", isHealthy ? "Healthy" : "Unhealthy")
} catch (error) {
console.error("Health check failed", error)
}
}
In this project, the health check endpoint is also utilized by Docker Compose to manage container dependencies:
# compose.yml
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/api/v1/utils/health-check/"]
interval: 10s
timeout: 5s
retries: 5
Test Email Configuration
To verify that your SMTP settings are correctly configured on the backend, use the testEmail method. This requires superuser privileges.
import { UtilsService } from "@/client"
const handleTestEmail = async (email: string) => {
try {
const response = await UtilsService.testEmail({ emailTo: email })
console.log(response.message) // "Test email sent"
} catch (error) {
// Handle 422 Validation Error or 403 Forbidden
console.error("Failed to send test email", error)
}
}
Provide Standardized UI Feedback
The useCustomToast hook provides a consistent way to display success and error notifications using the sonner library.
import useCustomToast from "@/hooks/useCustomToast"
const MyComponent = () => {
const { showSuccessToast, showErrorToast } = useCustomToast()
const handleAction = async () => {
try {
// Perform operation...
showSuccessToast("Operation completed successfully!")
} catch (err) {
showErrorToast("The operation failed. Please try again.")
}
}
}
This hook is frequently used in conjunction with handleError for API mutations, as seen in useAuth.ts:
// frontend/src/hooks/useAuth.ts
const { showErrorToast } = useCustomToast()
const signUpMutation = useMutation({
mutationFn: (data: UserRegister) =>
UsersService.registerUser({ requestBody: data }),
onError: handleError.bind(showErrorToast), // Automatically shows error toast
})
Copy Text to Clipboard
Use the useCopyToClipboard hook to implement "Copy to Clipboard" functionality with a built-in success state that resets after 2 seconds.
import { useCopyToClipboard } from "@/hooks/useCopyToClipboard"
const CopyButton = ({ textToCopy }: { textToCopy: string }) => {
const [copiedText, copy] = useCopyToClipboard()
return (
<button onClick={() => copy(textToCopy)}>
{copiedText ? "Copied!" : "Copy to Clipboard"}
</button>
)
}
Detect Mobile Viewports
The useIsMobile hook allows you to conditionally render components or logic based on the screen width (breakpoint set at 768px).
import { useIsMobile } from "@/hooks/useMobile"
const ResponsiveComponent = () => {
const isMobile = useIsMobile()
return (
<div>
{isMobile ? <MobileNavigation /> : <DesktopSidebar />}
</div>
)
}
Troubleshooting
Email Testing Fails
- Permissions: Ensure the authenticated user has superuser privileges. The
testEmailendpoint is restricted to administrative accounts. - Configuration: If the request succeeds but no email is received, check the
EMAILS_ENABLEDand SMTP environment variables in your.envfile.
Clipboard Not Working
- Secure Contexts: The
navigator.clipboardAPI used byuseCopyToClipboardrequires a secure context (HTTPS or localhost). It will log a warning and returnfalsein non-secure environments.
Health Check Timeouts
- Infrastructure: If Docker Compose reports the backend as unhealthy, ensure the
curlcommand is available in the backend container and that thePORTmatches the one defined incompose.yml.