wisperlink-app / src /lib /consumption.ts
looda3131's picture
اجعله بسيطا قدر الامكان وذكيا يعني كل استعدعاء + +1
2676d60
'use client';
const DAILY_LIMIT = 200;
const CONSUMPTION_STORAGE_KEY = 'aiApiConsumption';
interface ConsumptionData {
date: string;
count: number;
}
function getConsumptionData(): ConsumptionData {
if (typeof window === 'undefined') {
// Return a state that disallows calls on server
return { date: '', count: DAILY_LIMIT };
}
const today = new Date().toISOString().split('T')[0];
try {
const storedData = localStorage.getItem(CONSUMPTION_STORAGE_KEY);
if (storedData) {
const parsed: ConsumptionData = JSON.parse(storedData);
if (parsed.date === today) {
return parsed;
}
}
} catch (e) {
console.error("Could not parse consumption data, resetting.", e);
}
// Return fresh data for a new day, or if no/bad data exists
return { date: today, count: 0 };
}
/**
* Checks if an API call is allowed and returns the number of remaining calls.
* Call this BEFORE making an API call.
*/
export const checkConsumption = (): { allowed: boolean; remaining: number } => {
const data = getConsumptionData();
const isAllowed = data.count < DAILY_LIMIT;
return {
allowed: isAllowed,
remaining: DAILY_LIMIT - data.count,
};
};
/**
* Smartly increments the daily API call counter by 1.
* Call this AFTER a successful API call.
*/
export const recordConsumption = () => {
if (typeof window === 'undefined') return;
const today = new Date().toISOString().split('T')[0];
const data = getConsumptionData();
if (data.date !== today) {
// It's a new day, this is the first call
localStorage.setItem(CONSUMPTION_STORAGE_KEY, JSON.stringify({ date: today, count: 1 }));
} else {
// It's the same day, just increment
data.count++;
localStorage.setItem(CONSUMPTION_STORAGE_KEY, JSON.stringify(data));
}
};