perf: remover polling de storage-stats e trabalho repetido na busca do cache
- useStorageMonitor: o efeito com setInterval de 10 s chamava /api/storage-stats em toda aba aberta só para escrever no console (nenhum estado é atualizado); o servidor faz fs.stat e conta as chaves do cache a cada chamada. A busca inicial de estatísticas continua. - JsonCacheManager.searchProducts: convertToAPIProduct rodava duas vezes por produto (filtro e map) e a relevância era recalculada, com toLowerCase, a cada comparação do sort; agora é uma vez por produto.
This commit is contained in:
1 parent
a9ab66e26f
commit
3d59903114
2 files changed
+13
-53
No files matched your search
@@ -86,44 +86,6 @@ export function useStorageMonitor(): UseStorageMonitorReturn {
|
||||
fetchStats();
|
||||
}, [fetchStats]);
|
||||
|
||||
// Monitoramento automático para todos os usuários
|
||||
useEffect(() => {
|
||||
let intervalId: NodeJS.Timeout | null = null;
|
||||
|
||||
const startMonitoring = async () => {
|
||||
// Executar imediatamente
|
||||
await fetchAndDisplayStats();
|
||||
|
||||
// Depois executar a cada 10 segundos
|
||||
intervalId = setInterval(async () => {
|
||||
await fetchAndDisplayStats();
|
||||
}, 10000);
|
||||
};
|
||||
|
||||
const fetchAndDisplayStats = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/storage-stats");
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
console.log(
|
||||
`[Monitor] Total de produtos no cache: ${data.data.totalProducts} produtos`
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[Monitor] Erro ao buscar estatísticas:", error);
|
||||
}
|
||||
};
|
||||
|
||||
startMonitoring();
|
||||
|
||||
return () => {
|
||||
if (intervalId) {
|
||||
clearInterval(intervalId);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
stats,
|
||||
isLoading,
|
||||
|
||||
+13
-15
@@ -235,33 +235,31 @@ export class JsonCacheManager {
|
||||
`[JSON Cache] Buscando: "${searchTerm}" (país: ${country || "todos"})`
|
||||
);
|
||||
|
||||
// Filtrar produtos
|
||||
// Filtrar produtos; a relevância é calculada uma vez por produto
|
||||
const filteredProducts = Object.values(this.cacheData.products)
|
||||
.filter((cachedProduct) => {
|
||||
const product = this.convertToAPIProduct(cachedProduct);
|
||||
|
||||
// Verificar se corresponde à query
|
||||
const matchesQuery =
|
||||
product.product_name?.toLowerCase().includes(searchTerm) ||
|
||||
product.brands?.toLowerCase().includes(searchTerm) ||
|
||||
product.categories?.toLowerCase().includes(searchTerm);
|
||||
cachedProduct.product_name?.toLowerCase().includes(searchTerm) ||
|
||||
cachedProduct.brands?.toLowerCase().includes(searchTerm) ||
|
||||
cachedProduct.categories?.toLowerCase().includes(searchTerm);
|
||||
|
||||
// Verificar país se especificado
|
||||
const matchesCountry =
|
||||
!country ||
|
||||
product.countries_tags?.includes(country) ||
|
||||
product.countries?.toLowerCase().includes(country.toLowerCase());
|
||||
cachedProduct.countries_tags?.includes(country) ||
|
||||
cachedProduct.countries?.toLowerCase().includes(country.toLowerCase());
|
||||
|
||||
return matchesQuery && matchesCountry;
|
||||
})
|
||||
.map((cachedProduct) => this.convertToAPIProduct(cachedProduct))
|
||||
// Ordenar por relevância
|
||||
.sort((a, b) => {
|
||||
const scoreA = this.calculateRelevanceScore(a, searchTerm);
|
||||
const scoreB = this.calculateRelevanceScore(b, searchTerm);
|
||||
return scoreB - scoreA;
|
||||
.map((cachedProduct) => {
|
||||
const product = this.convertToAPIProduct(cachedProduct);
|
||||
return { product, score: this.calculateRelevanceScore(product, searchTerm) };
|
||||
})
|
||||
.slice(0, limit);
|
||||
// Ordenar por relevância
|
||||
.sort((a, b) => b.score - a.score)
|
||||
.slice(0, limit)
|
||||
.map(({ product }) => product);
|
||||
|
||||
console.log(
|
||||
`[JSON Cache] Encontrados ${filteredProducts.length} produtos`
|
||||
|
||||
Reference in new issue
Block a user