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