Files
pfm/PostFundManagement.Application/Services/Shared/IdentityCacheService.cs
T

32 lines
1.2 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
using PostFundManagement.Application.Abstractions.Services;
using PostFundManagement.Domain.Errors;
namespace PostFundManagement.Application.Services.Shared;
public sealed class IdentityCacheService(IdentityService service, IDistributedCache cache) : IIdentityService
{
public async ValueTask<Result> UserIsAuthorisedAsync(Guid userId, CancellationToken cancellationToken = default) =>
await Result.Try((Func<ValueTask<Result>>)(async () =>
{
var cacheKey = HashService.ToMd5Hash($"userisauthorised-{userId}").Value;
var cached = await cache.GetStringAsync(cacheKey);
if (string.IsNullOrWhiteSpace(cached))
{
var result = await service.UserIsAuthorisedAsync(userId, cancellationToken); ;
if (result.IsFailed) return result;
await cache.SetStringAsync(cacheKey, "true", cancellationToken);
return Result.Ok();
}
return cached.Equals("true", StringComparison.OrdinalIgnoreCase)
? Result.Ok()
: Result.Fail(NotFoundError.New);
}));
}