using System.Text; using System.Text.Json; using AutoCat.Model.Requests; using AutoCatCore.Model; using AutoCatCore.Model.Requests; using AutoCatCore.Services.Storage; namespace AutoCatCore.Services.Api; public class ApiService : IApiService { private readonly HttpClient _httpClient; public ApiService(IStorageService storageService) { _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri("https://vps.aliencat.pro:8443"); SetAccessToken(storageService.AuthToken); } private static T GetDataOrThrow(string response) { var resp = JsonSerializer.Deserialize>(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 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(respStr); SetAccessToken(result.Token); return result; } public async Task> GetVehicles() { var response = await _httpClient.GetAsync("vehicles"); var respStr = await response.Content.ReadAsStringAsync(); return GetDataOrThrow>(respStr); } }