import {Customer} from "@/services/customers/entities/customer"; import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto"; export class CustomerRepository { private static readonly customerCache: Map = new Map(); private static lastFetchAll: number | null = null; private static readonly CACHE_DURATION = 10 * 1000; // seconds in milliseconds static async getAll(): Promise { const now = Date.now(); if (this.lastFetchAll && (now - this.lastFetchAll < this.CACHE_DURATION)) { return Array.from(this.customerCache.values()); } console.log('Cache expired or not initialized, fetching fresh data from API'); const response = await fetch('/api/customers'); if (!response.ok) { console.error('Failed to fetch customers:', response.status, response.statusText); return Promise.reject(new Error(`Failed to fetch customers: ${response.statusText}`)); } const customers: Customer[] = await response.json(); this.customerCache.clear(); customers.forEach((customer: Customer) => this.customerCache.set(customer.id, customer)); this.lastFetchAll = now; return customers; } static async getById(id: string): Promise { const cachedCustomer = this.customerCache.get(id); if (cachedCustomer) { return cachedCustomer; } console.log(`Cache miss for customer ${id}, fetching from API`); try { const response = await fetch(`/api/customers/${id}`); if (!response.ok) { if (response.status === 404) { console.log(`Customer ${id} not found`); return null; } console.error('Failed to fetch customer:', response.status, response.statusText); return Promise.reject(new Error(`Failed to fetch customer: ${response.statusText}`)); } const customer: Customer = await response.json(); this.customerCache.set(id, customer); return customer; } catch (error) { console.error('Error fetching customer:', error); return Promise.reject(error); } } static async create(payload: CreateCustomerDto): Promise { const response = await fetch('/api/customers', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload) }); if (!response.ok) { console.error('Failed to create customer:', response.status, response.statusText); return Promise.reject(new Error(`Failed to create customer: ${response.statusText}`)); } console.log('Cache invalidated after creating new customer'); this.lastFetchAll = null; // Invalidate the cache after creating new customer } static clearCache(): void { console.log('Cache manually cleared'); this.customerCache.clear(); this.lastFetchAll = null; } static updateCache(customer: Customer): void { console.log(`Cache updated for customer ${customer.id}`); this.customerCache.set(customer.id, customer); } }