30 lines
917 B
JavaScript
30 lines
917 B
JavaScript
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
|
|
const logPath = path.join(process.cwd(), 'data', 'request-log.json');
|
|
const maximumEntries = 500;
|
|
|
|
async function loadEntries() {
|
|
try {
|
|
return JSON.parse(await readFile(logPath, 'utf8'));
|
|
} catch (error) {
|
|
if (error.code === 'ENOENT') return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function recordRequest(entry) {
|
|
const entries = await loadEntries();
|
|
entries.push(entry);
|
|
await mkdir(path.dirname(logPath), { recursive: true });
|
|
await writeFile(logPath, `${JSON.stringify(entries.slice(-maximumEntries), null, 2)}\n`, { mode: 0o600 });
|
|
}
|
|
|
|
export async function recentRequests(limit = 50) {
|
|
return (await loadEntries()).slice(-limit).reverse();
|
|
}
|
|
|
|
export async function clearRequests() {
|
|
await mkdir(path.dirname(logPath), { recursive: true });
|
|
await writeFile(logPath, '[]\n', { mode: 0o600 });
|
|
} |