wulf-pulse/autotask-app/lib/services/redis-client.ts

100 lines
2.4 KiB
TypeScript
Raw Normal View History

Add Addigy API integration and Docker deployment with Redis caching - Implemented complete Addigy API v2 client with authentication via x-api-key - Added device and policy endpoints with automatic org ID resolution - Created field mapping from snake_case to Title Case for UI compatibility - Handles nested 'facts' response structure from Addigy devices API - Added comprehensive API documentation in ADDIGY_API_GUIDE.md - Multi-stage Dockerfile with optimized production build - Custom ports: App on 3100, Redis on 6380 (avoids conflicts) - Docker Compose orchestration with health checks - Standalone Next.js output for smaller container images - Non-root user execution for security - Implemented Redis caching layer for API responses - 5-minute TTL with graceful fallback if Redis unavailable - Cache key structure: service:entity:filter1:filter2 - Applied to Addigy devices endpoint with cache hit/miss logging - Fixed TypeScript strict mode errors for production builds - Added null safety checks with optional chaining throughout API routes - Wrapped useSearchParams in Suspense boundary for Next.js 15+ compatibility - Fixed type assertions for dynamic API responses - Corrected Set<string> type mismatches in device comparison logic - Created DOCKER_README.md with complete deployment guide - Updated ADDIGY_API_GUIDE.md with real-world API patterns - Documented response structures, field mappings, and troubleshooting - Next.js 16.0.0 with Turbopack - Redis 7 with AOF persistence - Podman/Docker compatible - TypeScript strict mode compliant
2025-10-28 22:49:08 -04:00
import Redis from 'ioredis';
let redisClient: Redis | null = null;
export function getRedisClient(): Redis | null {
if (!process.env.REDIS_URL) {
console.log('Redis URL not configured, caching disabled');
return null;
}
if (!redisClient) {
try {
redisClient = new Redis(process.env.REDIS_URL, {
maxRetriesPerRequest: 3,
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000);
return delay;
},
reconnectOnError: (err) => {
const targetError = 'READONLY';
if (err.message.includes(targetError)) {
// Only reconnect when the error contains "READONLY"
return true;
}
return false;
},
});
redisClient.on('error', (err) => {
console.error('Redis Client Error:', err);
});
redisClient.on('connect', () => {
console.log('Redis Client Connected');
});
} catch (error) {
console.error('Failed to initialize Redis client:', error);
return null;
}
}
return redisClient;
}
export async function getCachedData<T>(key: string): Promise<T | null> {
const client = getRedisClient();
if (!client) return null;
try {
const data = await client.get(key);
if (data) {
return JSON.parse(data);
}
} catch (error) {
console.error(`Error getting cached data for key ${key}:`, error);
}
return null;
}
export async function setCachedData<T>(
key: string,
data: T,
ttlSeconds: number = 300 // Default 5 minutes
): Promise<void> {
const client = getRedisClient();
if (!client) return;
try {
await client.set(key, JSON.stringify(data), 'EX', ttlSeconds);
} catch (error) {
console.error(`Error setting cached data for key ${key}:`, error);
}
}
export async function deleteCachedData(pattern: string): Promise<void> {
const client = getRedisClient();
if (!client) return;
try {
const keys = await client.keys(pattern);
if (keys.length > 0) {
await client.del(...keys);
}
} catch (error) {
console.error(`Error deleting cached data for pattern ${pattern}:`, error);
}
}
export async function flushCache(): Promise<void> {
const client = getRedisClient();
if (!client) return;
try {
await client.flushdb();
console.log('Cache flushed successfully');
} catch (error) {
console.error('Error flushing cache:', error);
}
}