You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.3 KiB
68 lines
2.3 KiB
using DealerSelection.Api.CommonUtil;
|
|
using DealerSelection.Api.Interface;
|
|
using DealerSelection.Api.Models;
|
|
using DealerSelection.Common.Interfaces.HttpClient;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace DealerSelection.Api;
|
|
|
|
public class MulesoftTokenApi : IMulesoftTokenApi
|
|
{
|
|
private readonly ILogger _logger;
|
|
private readonly IMemoryCache cache;
|
|
IHttpClientHandler ClientHandler { get; }
|
|
|
|
public MulesoftTokenApi(IMemoryCache cache, IHttpClientHandler clientHandler
|
|
, ILogger<MulesoftTokenApi> logger)
|
|
{
|
|
this.cache = cache;
|
|
ClientHandler = clientHandler;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<string> FetchToken()
|
|
{
|
|
string token = string.Empty;
|
|
try
|
|
{
|
|
// if cache doesn't contain
|
|
// an entry called TOKEN
|
|
// error handling mechanism is mandatory
|
|
if (!cache.TryGetValue("TOKEN", out token))
|
|
{
|
|
var tokenmodel = await GetTokenFromApi();
|
|
// keep the value within cache for
|
|
// given amount of time
|
|
// if value is not accessed within the expiry time
|
|
// delete the entry from the cache
|
|
if (tokenmodel.ExpiresIn > 0)
|
|
{
|
|
var options = new MemoryCacheEntryOptions()
|
|
.SetAbsoluteExpiration(
|
|
TimeSpan.FromSeconds(tokenmodel.ExpiresIn - 300));
|
|
|
|
cache.Set("TOKEN", tokenmodel.Value, options);
|
|
|
|
token = tokenmodel.Value;
|
|
|
|
_logger.LogInformation("MulesoftTokenApi at FetchToken - token Generated Successfully :- " + DateTime.Now);
|
|
}
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError("MulesoftTokenApi Api:- FetchToken:- " + ex.Message.ToString());
|
|
}
|
|
return token;
|
|
}
|
|
|
|
private async Task<MulesoftToken> GetTokenFromApi()
|
|
{
|
|
// get api implementation happens here
|
|
// returns a token model
|
|
_logger.LogInformation("MulesoftTokenApi at GetTokenFromApi Started :- " + DateTime.Now);
|
|
MulesoftToken token = await MuleSoftIntegration.generateToken(ClientHandler);
|
|
return token;
|
|
}
|
|
}
|