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:
2025-07-07 22:02:55 +02:00
parent 4ae62f2911
commit 328c0537ba
4 changed files with 106 additions and 35 deletions

View File

@@ -1,19 +1,17 @@
"use client"; "use client";
import React, {useEffect, useState, useMemo} from "react"; import React, {useEffect, useState} from "react";
import {useParams, useRouter} from "next/navigation"; import {useParams, useRouter} from "next/navigation";
import {ChevronLeft} from "lucide-react"; import {ChevronLeft} from "lucide-react";
import axios, {AxiosError} from "axios";
import {Button} from "@/components/ui/button"; import {Button} from "@/components/ui/button";
import {Dialog} from "@/components/ui/dialog"; import {Dialog} from "@/components/ui/dialog";
import {Skeleton} from "@/components/ui/skeleton"; import {Skeleton} from "@/components/ui/skeleton";
import CustomerDetailContent from "@/components/customers/details/CustomerDetailContent"; import CustomerDetailContent from "@/components/customers/details/CustomerDetailContent";
import {Customer} from "@/services/customers/entities/customer";
import CustomerInformationContent from "@/components/customers/details/sub/ContactInformationContent"; import CustomerInformationContent from "@/components/customers/details/sub/ContactInformationContent";
import CustomerPhoneNumberContent from "@/components/customers/details/sub/CustomerPhoneNumberContent"; import CustomerPhoneNumberContent from "@/components/customers/details/sub/CustomerPhoneNumberContent";
import CustomerNotesContent from "@/components/customers/details/sub/CustomerNotesContent"; import CustomerNotesContent from "@/components/customers/details/sub/CustomerNotesContent";
import {Customer} from "@/services/customers/entities/customer";
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || '/api'; import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export default function CustomerDetailPage() { export default function CustomerDetailPage() {
const router = useRouter(); const router = useRouter();
@@ -35,23 +33,22 @@ export default function CustomerDetailPage() {
setLoading(true); setLoading(true);
setError(null); setError(null);
axios CustomerRepository.getById(id)
.get<Customer>(`${API_BASE_URL}/customers/${id}`) .then((result) => {
.then((res) => { if (!isMounted) return;
if (isMounted) {
setCustomer(res.data); if (!result) {
setError("Kunde nicht gefunden");
setCustomer(null);
} else {
setCustomer(result);
} }
}) })
.catch((error: AxiosError) => { .catch((error) => {
if (isMounted) { if (!isMounted) return;
console.error('Error fetching customer:', error); console.error('Error fetching customer:', error);
setCustomer(null); setCustomer(null);
setError( setError("Fehler beim Laden der Kundendaten");
error.response?.status === 404
? "Kunde nicht gefunden"
: "Fehler beim Laden der Kundendaten"
);
}
}) })
.finally(() => { .finally(() => {
if (isMounted) { if (isMounted) {
@@ -85,14 +82,14 @@ export default function CustomerDetailPage() {
} }
}; };
const customerMetadata = useMemo(() => ({ const customerMetadata = {
createdInfo: customer createdInfo: customer
? `Erstellt von ${customer.createdBy || "-"} am ${formatDate(customer.createdAt)}` ? `Erstellt von ${customer.createdBy || "-"} am ${formatDate(customer.createdAt)}`
: "Erstellt von - am -", : "Erstellt von - am -",
lastActivityInfo: customer lastActivityInfo: customer
? `Letzte Aktivität: ${customer.updatedBy || "-"} am ${formatDate(customer.updatedAt)}` ? `Letzte Aktivität: ${customer.updatedBy || "-"} am ${formatDate(customer.updatedAt)}`
: "Letzte Aktivität: - am -" : "Letzte Aktivität: - am -"
}), [customer]); };
const renderMetadata = () => { const renderMetadata = () => {
if (loading) { if (loading) {

View File

@@ -22,9 +22,9 @@ import {
import {motion} from "framer-motion"; import {motion} from "framer-motion";
import {ArrowRight} from "lucide-react"; import {ArrowRight} from "lucide-react";
import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal"; import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal";
import axios from "axios";
import {Customer} from "@/services/customers/entities/customer"; import {Customer} from "@/services/customers/entities/customer";
import Link from "next/link"; import Link from "next/link";
import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export default function CustomersPage() { export default function CustomersPage() {
const [customers, setCustomers] = useState<Customer[]>([]); const [customers, setCustomers] = useState<Customer[]>([]);
@@ -35,9 +35,9 @@ export default function CustomersPage() {
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
axios.get("/api/customers") CustomerRepository.getAll()
.then((res) => { .then((data) => {
setCustomers(res.data); setCustomers(data);
}) })
.catch((error) => { .catch((error) => {
console.error('Error fetching customers:', error); console.error('Error fetching customers:', error);

View File

@@ -1,4 +1,4 @@
import {customerRoutes} from "@/app/api/customers/customerRoutes"; import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export const breadcrumbMap: Record<string, string> = { export const breadcrumbMap: Record<string, string> = {
'dashboard': 'Dashboard', 'dashboard': 'Dashboard',
@@ -10,8 +10,9 @@ export const breadcrumbMap: Record<string, string> = {
export const breadcrumbResolvers: Record<string, (id: string) => Promise<string>> = { export const breadcrumbResolvers: Record<string, (id: string) => Promise<string>> = {
"customers": async (id: string) => { "customers": async (id: string) => {
const res = await fetch(`/api${customerRoutes.getById(id)}`, {cache: "no-store"}); const customer = await CustomerRepository.getById(id);
const customer = await res.json(); if (!customer) return `ID: ${id}`;
if (customer.companyName) return `Firma: ${customer.companyName}`; if (customer.companyName) return `Firma: ${customer.companyName}`;
if (customer.name) return `Name: ${customer.name}`; if (customer.name) return `Name: ${customer.name}`;
return `ID: ${id}`; return `ID: ${id}`;

View File

@@ -1,13 +1,86 @@
import {Customer} from "@/services/customers/entities/customer"; import {Customer} from "@/services/customers/entities/customer";
import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto"; import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto";
import {callApi} from "@/lib/api/callApi";
export class CustomerRepository { 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[]> { 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> { 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);
} }
} }