83 lines
1.8 KiB
TypeScript
83 lines
1.8 KiB
TypeScript
// Cache pour les associations PAT -> userId intégré au contexte GraphQL
|
|
export interface PATCacheEntry {
|
|
userId: string;
|
|
expiry: number;
|
|
}
|
|
|
|
class PATContextCache {
|
|
private cache: Map<string, PATCacheEntry> = new Map();
|
|
|
|
// Enregistrer une association PAT -> userId
|
|
register(pat: string, userId: string, ttlHours: number = 24): void {
|
|
this.cache.set(pat, {
|
|
userId: userId,
|
|
expiry: Date.now() + ttlHours * 60 * 60 * 1000,
|
|
});
|
|
}
|
|
|
|
// Récupérer l'userId depuis un PAT
|
|
getUserId(pat: string): string | null {
|
|
const entry = this.cache.get(pat);
|
|
if (entry && Date.now() < entry.expiry) {
|
|
return entry.userId;
|
|
}
|
|
|
|
// Supprimer l'entrée expirée
|
|
if (entry) {
|
|
this.cache.delete(pat);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
// Supprimer une entrée du cache
|
|
remove(pat: string): void {
|
|
this.cache.delete(pat);
|
|
}
|
|
|
|
// Nettoyer les entrées expirées
|
|
cleanup(): void {
|
|
const now = Date.now();
|
|
for (const [pat, entry] of this.cache.entries()) {
|
|
if (now >= entry.expiry) {
|
|
this.cache.delete(pat);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Obtenir les statistiques du cache
|
|
getStats(): { size: number; entries: number } {
|
|
this.cleanup(); // Nettoyer avant de retourner les stats
|
|
return {
|
|
size: this.cache.size,
|
|
entries: this.cache.size,
|
|
};
|
|
}
|
|
|
|
// Vérifier si un PAT existe dans le cache
|
|
has(pat: string): boolean {
|
|
const entry = this.cache.get(pat);
|
|
if (entry && Date.now() < entry.expiry) {
|
|
return true;
|
|
}
|
|
|
|
// Supprimer l'entrée expirée
|
|
if (entry) {
|
|
this.cache.delete(pat);
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Instance singleton du cache PAT
|
|
export const patContextCache = new PATContextCache();
|
|
|
|
// Nettoyer le cache toutes les heures
|
|
setInterval(
|
|
() => {
|
|
patContextCache.cleanup();
|
|
},
|
|
60 * 60 * 1000
|
|
); // 1 heure
|