Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/foundation/src/audit.ts
T

49 lines
1.5 KiB
TypeScript

import type { JsonValue } from "./errors.js";
export type AuditEventInput = {
tenantId?: string | null;
actorId?: string | null;
actorType?: string | null;
action: string;
targetType?: string | null;
targetId?: string | null;
requestId?: string | null;
metadata?: Record<string, JsonValue> | null;
};
export type AuditEventClient = {
auditEvent: {
create(args: {
data: Required<Pick<AuditEventInput, "actorType" | "action">> & Omit<AuditEventInput, "actorType" | "action">;
}): Promise<unknown>;
};
};
export async function auditEvent(input: AuditEventInput, client: AuditEventClient): Promise<unknown> {
return client.auditEvent.create({
data: {
tenantId: input.tenantId ?? null,
actorId: input.actorId ?? null,
actorType: input.actorType?.trim() || "system",
action: input.action,
targetType: input.targetType ?? null,
targetId: input.targetId ?? null,
requestId: input.requestId ?? null,
metadata: input.metadata ?? null,
},
});
}
export function withAuditMiddleware<TArgs extends readonly unknown[], TResult>(
handler: (...args: TArgs) => Promise<TResult>,
buildEvent: (result: TResult, args: TArgs) => AuditEventInput | null | undefined,
client: AuditEventClient,
): (...args: TArgs) => Promise<TResult> {
return async (...args) => {
const result = await handler(...args);
const event = buildEvent(result, args);
if (event) await auditEvent(event, client);
return result;
};
}