Refactor categories view with tree structure and improve product caching

This commit is contained in:
masoodafar-web
2025-11-28 12:35:34 +03:30
parent 6ab835f7e9
commit 12d19f966c
6 changed files with 199 additions and 82 deletions

View File

@@ -25,7 +25,7 @@ public class CategoryService
}
var response = await _client.GetAllCategoriesAsync(new GetCategoriesRequest());
_cache = response.Categories
_cache = response.Models
.Select(dto => new CategoryItem(
Id: dto.Id,
Title: dto.Title ?? dto.Name ?? string.Empty,

View File

@@ -98,7 +98,10 @@ public class ProductService
public async Task<Product?> GetByIdAsync(long id)
{
if (TryGetCachedProduct(id, out var cached)) return cached;
if (TryGetCachedProduct(id, out var cached) && HasDetailedData(cached))
{
return cached;
}
try
{
@@ -112,6 +115,11 @@ public class ProductService
}
catch
{
if (cached is not null)
{
return cached;
}
TryGetCachedProduct(id, out var result);
return result;
}
@@ -134,6 +142,8 @@ public class ProductService
Rate: m.Rate,
RemainingCount: m.RemainingCount
);
p = PreserveCachedDetails(p);
CacheProduct(p);
list.Add(p);
@@ -142,6 +152,27 @@ public class ProductService
return list;
}
private Product PreserveCachedDetails(Product product)
{
if (_cache.TryGetValue(product.Id, out var entry))
{
var cached = entry.Product;
var hasGallery = cached.Gallery.Count > 0;
var hasCategories = cached.Categories.Count > 0;
if (hasGallery || hasCategories)
{
product = product with
{
Gallery = hasGallery ? cached.Gallery : product.Gallery,
Categories = hasCategories ? cached.Categories : product.Categories
};
}
}
return product;
}
private Product MapAndCache(GetProductsResponse model)
{
var gallery = model.Gallery
@@ -202,6 +233,9 @@ public class ProductService
.Where(entry => entry.Expiration > now)
.Select(entry => entry.Product);
}
private static bool HasDetailedData(Product product)
=> product.Gallery.Count > 0 || product.Categories.Count > 0;
private sealed record CacheEntry(Product Product, DateTime Expiration);
private static string BuildUrl(string? path) =>