This repository has been archived on 2025-05-19. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
novaloop.paymoapi/src/Shared/BaseApi.cs

80 lines
2.9 KiB
C#

using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Novaloop.PaymoApi.Extensions;
namespace Novaloop.PaymoApi.Shared
{
public class BaseApi<TReturnType, TCreatType> : IBaseApi<TReturnType, TCreatType>
{
public string ResourceUri { get; set; }
private readonly ApiOptions _options;
private readonly HttpClient _client;
public BaseApi(ApiClient apiClient, IOptions<ApiOptions> options)
{
_options = options.Value;
_client = apiClient.Client;
}
/// <summary>
/// Receive all entities
/// </summary>
public async Task<TReturnType> GetAll()
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.GetAsync($"api/{ResourceUri}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Retrieve an existing entity
/// </summary>
/// <param name="entityId">id of the entity</param>
/// <returns></returns>
public async Task<TReturnType> Get(int entityId)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.GetAsync($"api/{ResourceUri}/{entityId}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Create a new entity
/// </summary>
public async Task<TReturnType> Create(TCreatType entity)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.PostAsJsonAsync($"api/{ResourceUri}", entity);
await response.ThrowExceptionWithDetailsIfUnsuccessful();
return await response.Content.ReadAsAsync<TReturnType>();
}
/// <summary>
/// Delete an entity
/// </summary>
/// <param name="entityId">id of the entity</param>
/// <returns></returns>
public async Task Delete(int entityId)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.DeleteAsync($"api/{ResourceUri}/{entityId}");
await response.ThrowExceptionWithDetailsIfUnsuccessful();
}
/// <summary>
/// Update an entity
/// </summary>
/// <param name="entity">entity information to update the entity with</param>
/// <param name="id">id of the entity to update</param>
/// <returns></returns>
public async Task Update(TCreatType entity, int id)
{
_client.SetApiKeyHeader(_options.ApiToken);
var response = await _client.PutAsJsonAsync($"api/{ResourceUri}/{id}", entity);
await response.ThrowExceptionWithDetailsIfUnsuccessful();
}
}
}