63 lines
2.0 KiB
C#
63 lines
2.0 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
using AutoCat.Model.Requests;
|
|
using AutoCatCore.Model;
|
|
using AutoCatCore.Model.Requests;
|
|
|
|
namespace AutoCatCore.Services.Api;
|
|
|
|
public class ApiService : IApiService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
|
|
public ApiService()
|
|
{
|
|
_httpClient = new HttpClient();
|
|
_httpClient.BaseAddress = new Uri("https://vps.aliencat.pro:8443");
|
|
}
|
|
|
|
private static T GetDataOrThrow<T>(string response)
|
|
{
|
|
var resp = JsonSerializer.Deserialize<Response<T>>(response, new JsonSerializerOptions {
|
|
PropertyNameCaseInsensitive = true
|
|
});
|
|
|
|
if (resp is null)
|
|
throw new Exception("Error deserializing response");
|
|
|
|
if (resp.Success)
|
|
return resp.Data ?? throw new Exception("Empty response");
|
|
|
|
throw new Exception(resp.Error);
|
|
}
|
|
|
|
private void SetAccessToken(string? token)
|
|
{
|
|
if (token is null)
|
|
return;
|
|
|
|
_httpClient.DefaultRequestHeaders.Remove("Authorization");
|
|
_httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
|
|
}
|
|
|
|
public async Task<User> Login(string email, string password)
|
|
{
|
|
var credentials = new Credentials { Email = email, Password = password };
|
|
var json = JsonSerializer.Serialize(credentials, new JsonSerializerOptions {
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
|
});
|
|
var content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
var response = await _httpClient.PostAsync("user/login", content);
|
|
var respStr = await response.Content.ReadAsStringAsync();
|
|
var result = GetDataOrThrow<User>(respStr);
|
|
SetAccessToken(result.Token);
|
|
return result;
|
|
}
|
|
|
|
public async Task<PagedResponse<Vehicle>> GetVehicles()
|
|
{
|
|
var response = await _httpClient.GetAsync("vehicles");
|
|
var respStr = await response.Content.ReadAsStringAsync();
|
|
return GetDataOrThrow<PagedResponse<Vehicle>>(respStr);
|
|
}
|
|
} |