using System.Net.Mime; using System.Text; using Microsoft.AspNetCore.WebUtilities; using Newtonsoft.Json; using Treestar.Shared.Models; namespace Treestar.Shared.AccessLayers; public abstract class ApiAccessLayer { private readonly HttpClient _httpClient; private readonly IAccessLayerAuthenticationProvider _authenticationProvider; protected ApiAccessLayer(string apiBaseUrl, IAccessLayerAuthenticationProvider authenticationProvider) { _authenticationProvider = authenticationProvider; var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; _httpClient = new HttpClient(handler); _httpClient.BaseAddress = new Uri(apiBaseUrl, UriKind.Absolute); } private async Task SendRequest(HttpRequestMessage message) { await _authenticationProvider.AddAuthentication(message); var response = await _httpClient.SendAsync(message); return new HttpResponseWrapper() { HttpResponseMessage = response }; } private async Task> SendRequest(HttpRequestMessage message) { var wrapper = await SendRequest(message); if (wrapper.HttpResponseMessage.IsSuccessStatusCode) { var parsedJson = JsonConvert.DeserializeObject(await wrapper.HttpResponseMessage.Content.ReadAsStringAsync()); return new HttpResponseWrapper { HttpResponseMessage = wrapper.HttpResponseMessage, ResponseObject = parsedJson }; } return new HttpResponseWrapper { HttpResponseMessage = wrapper.HttpResponseMessage, ResponseObject = default(T) }; } protected HttpRequestMessage CreateRequestMessage(string endpoint, HttpMethod method, Dictionary? queryParams = null, object? data = null) { HttpRequestMessage message = new HttpRequestMessage(); string uri = endpoint; if (queryParams != null) { uri = QueryHelpers.AddQueryString(endpoint, queryParams); } message.RequestUri = new Uri(uri, UriKind.Relative); message.Method = method; if (data != null) { message.Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, MediaTypeNames.Application.Json); } return message; } protected async Task SendRequest(string endpoint, HttpMethod method, Dictionary? queryParams = null, object? data = null) { HttpRequestMessage message = CreateRequestMessage(endpoint, method, queryParams, data); return await SendRequest(message); } protected async Task> SendRequest(string endpoint, HttpMethod method, Dictionary? queryParams = null, object? data = null) { HttpRequestMessage message = CreateRequestMessage(endpoint, method, queryParams, data); return await SendRequest(message); } }