Introduce caching in CustomerRepository and refactor API integration
- Add in-memory caching for customer data in `CustomerRepository` to reduce API calls. - Replace direct API calls with methods from `CustomerRepository`. - Update customer-related pages (`[id]/page.tsx`, `customers/page.tsx`) to use `CustomerRepository` for data fetching. - Adjust breadcrumb resolver to leverage `CustomerRepository`. - Remove `axios` dependency from customer-related components.
This commit is contained in:
@@ -1,13 +1,86 @@
|
||||
import {Customer} from "@/services/customers/entities/customer";
|
||||
import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto";
|
||||
import {callApi} from "@/lib/api/callApi";
|
||||
|
||||
export class CustomerRepository {
|
||||
private static readonly customerCache: Map<string, Customer> = new Map();
|
||||
private static lastFetchAll: number | null = null;
|
||||
private static readonly CACHE_DURATION = 10 * 1000; // seconds in milliseconds
|
||||
|
||||
static async getAll(): Promise<Customer[]> {
|
||||
return await callApi<Customer[]>("/customers", "GET");
|
||||
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<Customer | null> {
|
||||
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<void> {
|
||||
await callApi<void, CreateCustomerDto>("/customers", "POST", payload);
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user