61 lines
1.3 KiB
TypeScript
61 lines
1.3 KiB
TypeScript
import { AsyncLocalStorage } from 'async_hooks';
|
|
|
|
/**
|
|
* Audit-Kontext für die Übertragung von Before/After-Werten
|
|
* zwischen Prisma-Middleware und Audit-Middleware
|
|
*/
|
|
export interface AuditContext {
|
|
before?: Record<string, unknown>;
|
|
after?: Record<string, unknown>;
|
|
}
|
|
|
|
// AsyncLocalStorage für den Audit-Kontext
|
|
const auditStorage = new AsyncLocalStorage<AuditContext>();
|
|
|
|
/**
|
|
* Startet einen neuen Audit-Kontext für einen Request
|
|
*/
|
|
export function runWithAuditContext<T>(fn: () => T): T {
|
|
return auditStorage.run({}, fn);
|
|
}
|
|
|
|
/**
|
|
* Setzt die "Before"-Werte im aktuellen Kontext
|
|
*/
|
|
export function setBeforeValues(values: Record<string, unknown>): void {
|
|
const context = auditStorage.getStore();
|
|
if (context) {
|
|
context.before = values;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Setzt die "After"-Werte im aktuellen Kontext
|
|
*/
|
|
export function setAfterValues(values: Record<string, unknown>): void {
|
|
const context = auditStorage.getStore();
|
|
if (context) {
|
|
context.after = values;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Holt den aktuellen Audit-Kontext
|
|
*/
|
|
export function getAuditContext(): AuditContext | undefined {
|
|
return auditStorage.getStore();
|
|
}
|
|
|
|
/**
|
|
* Express Middleware zum Initialisieren des Audit-Kontexts
|
|
*/
|
|
export function auditContextMiddleware(
|
|
req: unknown,
|
|
res: unknown,
|
|
next: () => void
|
|
): void {
|
|
runWithAuditContext(() => {
|
|
next();
|
|
});
|
|
}
|