← back to Freddy
lib/audit.ts
30 lines
import { query } from './db';
/**
* Log an audit event to the audit_events table.
*/
export async function auditLog(
eventType: string,
entityType: string,
entityId: string | null,
metadata?: Record<string, unknown>,
ipAddress?: string,
): Promise<void> {
const metaJson = metadata ? JSON.stringify(metadata) : null;
console.log(
`[audit] ${eventType} | ${entityType} | ${entityId ?? '(none)'} | ip=${ipAddress ?? 'unknown'}`,
metadata ? JSON.stringify(metadata) : '',
);
try {
await query(
`INSERT INTO audit_events (event_type, entity_type, entity_id, metadata, ip_address)
VALUES ($1, $2, $3, $4, $5)`,
[eventType, entityType, entityId, metaJson, ipAddress ?? null],
);
} catch (err) {
console.error('[audit] Failed to write audit event:', (err as Error).message);
}
}