2016-05-02 09:52:09 +03:00
|
|
|
|
using System;
|
2016-05-03 00:50:16 +03:00
|
|
|
|
using System.Collections.Generic;
|
2016-05-06 07:17:38 +03:00
|
|
|
|
using System.Linq;
|
2016-05-02 09:52:09 +03:00
|
|
|
|
using System.Net.Http;
|
2016-05-06 07:17:38 +03:00
|
|
|
|
using System.Net.Http.Headers;
|
|
|
|
|
using System.Text;
|
2016-05-02 09:52:09 +03:00
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using Bit.App.Models.Api;
|
|
|
|
|
using ModernHttpClient;
|
|
|
|
|
using Newtonsoft.Json;
|
|
|
|
|
|
2016-05-06 07:17:38 +03:00
|
|
|
|
namespace Bit.App.Repositories
|
2016-05-02 09:52:09 +03:00
|
|
|
|
{
|
2016-05-06 07:17:38 +03:00
|
|
|
|
public abstract class BaseApiRepository
|
2016-05-02 09:52:09 +03:00
|
|
|
|
{
|
2016-05-06 07:17:38 +03:00
|
|
|
|
public BaseApiRepository()
|
2016-05-02 09:52:09 +03:00
|
|
|
|
{
|
|
|
|
|
Client = new HttpClient(new NativeMessageHandler());
|
|
|
|
|
Client.BaseAddress = new Uri("https://api.bitwarden.com");
|
2016-05-06 07:17:38 +03:00
|
|
|
|
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
2016-05-02 09:52:09 +03:00
|
|
|
|
}
|
|
|
|
|
|
2016-05-06 07:17:38 +03:00
|
|
|
|
protected virtual HttpClient Client { get; private set; }
|
|
|
|
|
protected abstract string ApiRoute { get; }
|
2016-05-02 09:52:09 +03:00
|
|
|
|
|
|
|
|
|
public async Task<ApiResult<T>> HandleErrorAsync<T>(HttpResponseMessage response)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
2016-05-03 00:50:16 +03:00
|
|
|
|
var errors = new List<ApiError>();
|
2016-06-14 03:03:16 +03:00
|
|
|
|
if(response.StatusCode == System.Net.HttpStatusCode.BadRequest)
|
2016-05-03 00:50:16 +03:00
|
|
|
|
{
|
2016-06-14 03:03:16 +03:00
|
|
|
|
var responseContent = await response.Content.ReadAsStringAsync();
|
|
|
|
|
var errorResponseModel = JsonConvert.DeserializeObject<ErrorResponse>(responseContent);
|
|
|
|
|
|
|
|
|
|
foreach(var valError in errorResponseModel.ValidationErrors)
|
2016-05-03 00:50:16 +03:00
|
|
|
|
{
|
2016-06-14 03:03:16 +03:00
|
|
|
|
foreach(var errorMessage in valError.Value)
|
|
|
|
|
{
|
|
|
|
|
errors.Add(new ApiError { Message = errorMessage });
|
|
|
|
|
}
|
2016-05-03 00:50:16 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return ApiResult<T>.Failed(response.StatusCode, errors.ToArray());
|
2016-05-02 09:52:09 +03:00
|
|
|
|
}
|
2016-05-03 00:50:16 +03:00
|
|
|
|
catch(JsonReaderException)
|
|
|
|
|
{ }
|
2016-05-02 09:52:09 +03:00
|
|
|
|
|
2016-05-03 00:50:16 +03:00
|
|
|
|
return ApiResult<T>.Failed(response.StatusCode, new ApiError { Message = "An unknown error has occured." });
|
2016-05-02 09:52:09 +03:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|