-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathCachedBasketRepository.cs
39 lines (29 loc) · 1.33 KB
/
CachedBasketRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
namespace Basket.API.Data;
public class CachedBasketRepository
(IBasketRepository repository, IDistributedCache cache)
: IBasketRepository
{
public async Task<ShoppingCart> GetBasket(string userName, CancellationToken cancellationToken = default)
{
var cachedBasket = await cache.GetStringAsync(userName, cancellationToken);
if (!string.IsNullOrEmpty(cachedBasket))
return JsonSerializer.Deserialize<ShoppingCart>(cachedBasket)!;
var basket = await repository.GetBasket(userName, cancellationToken);
await cache.SetStringAsync(userName, JsonSerializer.Serialize(basket), cancellationToken);
return basket;
}
public async Task<ShoppingCart> StoreBasket(ShoppingCart basket, CancellationToken cancellationToken = default)
{
await repository.StoreBasket(basket, cancellationToken);
await cache.SetStringAsync(basket.UserName, JsonSerializer.Serialize(basket), cancellationToken);
return basket;
}
public async Task<bool> DeleteBasket(string userName, CancellationToken cancellationToken = default)
{
await repository.DeleteBasket(userName, cancellationToken);
await cache.RemoveAsync(userName, cancellationToken);
return true;
}
}