81 lines
2.1 KiB
TypeScript
81 lines
2.1 KiB
TypeScript
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<T>(
|
|
method: string,
|
|
cache: CacheInterface<T>,
|
|
cacheKey: string,
|
|
operation: () => Promise<T>,
|
|
errorMessage: string,
|
|
context?: Record<string, unknown>
|
|
): Promise<T> {
|
|
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<T>(
|
|
cache: CacheInterface<T>,
|
|
cacheKey: string,
|
|
operation: () => Promise<T>,
|
|
errorMessage: string
|
|
): Promise<T> {
|
|
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);
|
|
}
|
|
}
|
|
}
|