using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Bit.App.Abstractions; using Bit.App.Models.Api; using Newtonsoft.Json; namespace Bit.App.Repositories { public abstract class ApiRepository : BaseApiRepository, IApiRepository where TId : IEquatable where TRequest : class where TResponse : class { public ApiRepository() { } public virtual async Task> GetByIdAsync(TId id) { var requestMessage = new TokenHttpRequestMessage() { Method = HttpMethod.Get, RequestUri = new Uri(Client.BaseAddress, string.Concat(ApiRoute, "/", id)), }; var response = await Client.SendAsync(requestMessage); if(!response.IsSuccessStatusCode) { return await HandleErrorAsync(response); } var responseContent = await response.Content.ReadAsStringAsync(); var responseObj = JsonConvert.DeserializeObject(responseContent); return ApiResult.Success(responseObj, response.StatusCode); } public virtual async Task>> GetAsync() { var requestMessage = new TokenHttpRequestMessage() { Method = HttpMethod.Get, RequestUri = new Uri(Client.BaseAddress, ApiRoute), }; var response = await Client.SendAsync(requestMessage); if(!response.IsSuccessStatusCode) { return await HandleErrorAsync>(response); } var responseContent = await response.Content.ReadAsStringAsync(); var responseObj = JsonConvert.DeserializeObject>(responseContent); return ApiResult>.Success(responseObj, response.StatusCode); } public virtual async Task> PostAsync(TRequest requestObj) { var requestMessage = new TokenHttpRequestMessage(requestObj) { Method = HttpMethod.Post, RequestUri = new Uri(Client.BaseAddress, ApiRoute), }; var response = await Client.SendAsync(requestMessage); if(!response.IsSuccessStatusCode) { return await HandleErrorAsync(response); } var responseContent = await response.Content.ReadAsStringAsync(); var responseObj = JsonConvert.DeserializeObject(responseContent); return ApiResult.Success(responseObj, response.StatusCode); } public virtual async Task> PutAsync(TId id, TRequest requestObj) { var requestMessage = new TokenHttpRequestMessage(requestObj) { Method = HttpMethod.Put, RequestUri = new Uri(Client.BaseAddress, string.Concat(ApiRoute, "/", id)), }; var response = await Client.SendAsync(requestMessage); if(!response.IsSuccessStatusCode) { return await HandleErrorAsync(response); } var responseContent = await response.Content.ReadAsStringAsync(); var responseObj = JsonConvert.DeserializeObject(responseContent); return ApiResult.Success(responseObj, response.StatusCode); } public virtual async Task> DeleteAsync(TId id) { var requestMessage = new TokenHttpRequestMessage() { Method = HttpMethod.Delete, RequestUri = new Uri(Client.BaseAddress, string.Concat(ApiRoute, "/", id)), }; var response = await Client.SendAsync(requestMessage); if(!response.IsSuccessStatusCode) { return await HandleErrorAsync(response); } return ApiResult.Success(null, response.StatusCode); } } }