import { dataServiceCalls, dataServiceDuration, } from "../monitoring/metrics.js"; import { logger } from "../monitoring/logger.js"; import { AdapterError } from "./errors.js"; import type { CacheInterface } from "./cache.js"; /** * Helper für DataService-Methoden mit Cache und Metrics */ export class DataServiceHelpers { /** * Führt eine DataService-Operation mit Cache und Metrics aus */ static async withCacheAndMetrics( method: string, cache: CacheInterface, cacheKey: string, operation: () => Promise, errorMessage: string, context?: Record ): Promise { const startTime = Date.now(); // Prüfe Cache const cached = await cache.get(cacheKey); if (cached) { dataServiceCalls.inc({ method, status: "success" }); dataServiceDuration.observe({ method }, (Date.now() - startTime) / 1000); return cached; } try { // Führe Operation aus const result = await operation(); // Speichere im Cache (wenn Ergebnis vorhanden) if (result) { await cache.set(cacheKey, result); } // Metrics dataServiceCalls.inc({ method, status: "success" }); dataServiceDuration.observe({ method }, (Date.now() - startTime) / 1000); return result; } catch (error) { // Error Metrics dataServiceCalls.inc({ method, status: "error" }); dataServiceDuration.observe({ method }, (Date.now() - startTime) / 1000); logger.error(`Error in ${method}`, { ...context, error }); throw new AdapterError(errorMessage, error); } } /** * Führt eine DataService-Operation nur mit Cache aus (ohne Metrics) */ static async withCache( cache: CacheInterface, cacheKey: string, operation: () => Promise, errorMessage: string ): Promise { const cached = await cache.get(cacheKey); if (cached) { return cached; } try { const result = await operation(); await cache.set(cacheKey, result); return result; } catch (error) { throw new AdapterError(errorMessage, error); } } }