Domina el caching en TypeScript al estilo Angular
Implementa un sistema de caching eficiente al estilo TanStack Query en tus proyectos TypeScript.
El código se ralentiza por peticiones repetidas a la misma API y necesitas optimizarlo.
El truco
// ANTES: Peticiones repetidas sin caching
async function fetchData(url: string): Promise<any> {
const response = await fetch(url);
return response.json();
}
// DESPUÉS: Implementación de caching
class Cache<T> {
private cache: Map<string, T>;
constructor() {
this.cache = new Map();
}
async fetchData(url: string, fetchFn: () => Promise<T>): Promise<T> {
if (this.cache.has(url)) {
return Promise.resolve(this.cache.get(url) as T);
}
const data = await fetchFn();
this.cache.set(url, data);
return data;
}
}
const cache = new Cache<any>();
async function fetchWithCache(url: string): Promise<any> {
return cache.fetchData(url, async () => {
const response = await fetch(url);
return response.json();
});
}
La clase Cache utiliza un Map para almacenar el resultado de las peticiones. Comprueba si ya existe un valor en caché antes de realizar una nueva petición. Si existe, devuelve el valor en caché; si no, realiza la petición y almacena el resultado. Esto reduce las peticiones duplicadas y mejora el rendimiento.
Implementar un sistema de caching eficiente en TypeScript puede marcar la diferencia en la velocidad y capacidad de respuesta de tus aplicaciones.