v2
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
import prisma from './db';
|
||||
|
||||
/**
|
||||
* Logs an API request to the database.
|
||||
* This is intentionally fire-and-forget — it never blocks the response path.
|
||||
*/
|
||||
export function logApiRequest(
|
||||
endpoint: string,
|
||||
status: number,
|
||||
duration: number
|
||||
): void {
|
||||
prisma.apiRequestLog
|
||||
.create({ data: { endpoint, status, duration } })
|
||||
.catch((error) => console.error('Failed to log API request:', error));
|
||||
|
||||
// Prune old logs in the background (keep last 7 days)
|
||||
pruneOldLogs();
|
||||
}
|
||||
|
||||
let lastPruneAt = 0;
|
||||
const PRUNE_INTERVAL = 60 * 60 * 1000; // prune at most once per hour
|
||||
|
||||
function pruneOldLogs(): void {
|
||||
if (Date.now() - lastPruneAt < PRUNE_INTERVAL) return;
|
||||
lastPruneAt = Date.now();
|
||||
|
||||
const cutoff = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
|
||||
prisma.apiRequestLog
|
||||
.deleteMany({ where: { createdAt: { lt: cutoff } } })
|
||||
.catch((error) => console.error('Failed to prune API logs:', error));
|
||||
}
|
||||
Reference in New Issue
Block a user