This document describes the shared utility functions available for use throughout the application. Using these shared utilities ensures consistent behavior and reduces code duplication.
The CacheManager provides efficient caching with metrics:
import { responseCache, knowledgeCache, createCache } from '../utils'
// Use predefined caches
responseCache.set('response:query', value)
const cachedValue = knowledgeCache.get('kb:topic')
// Create custom cache
const myCache = createCache({ maxSize: 100, ttl: 60000 })Safe JSON utilities to prevent errors:
import { safeJsonParse, extractJsonFromText, makeSerializable } from '../utils'
// Safe parsing with fallback
const data = safeJsonParse(text, { fallback: 'value' })
// Extract JSON from text that may contain other content
const jsonData = extractJsonFromText(aiResponse)
// Make objects safe for serialization (handles BigInt, circular refs)
const serializable = makeSerializable(complexObject)Standardized error handling:
import { ErrorType, createErrorResponse, handleProcessingError } from '../utils'
try {
// Your code
} catch (error) {
return handleProcessingError(error, context, 'componentName')
}import { withTimeout } from '../utils'
// Prevent hanging on slow external services
const result = await withTimeout(apiCall(), 5000, 'API request')- Always use shared utilities instead of reimplementing common functionality
- Import from the index file (
../utils) rather than individual utility files - Add metrics and monitoring for performance-sensitive operations
- Handle errors consistently using the standardized error handlers
- Document new utilities when adding them to the shared library
When adding new utility functions:
- Place them in the appropriate file in the
utilsdirectory - Export them in the
utils/index.jsfile - Add documentation to this file
- Add unit tests if applicable
- Use the
memoizeutility for expensive, frequently-called functions with stable inputs - Set appropriate TTL values for cached items based on data volatility
- Consider memory usage when caching large objects
- Use the built-in metrics to monitor cache performance