using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace PlanTempus.Application.Components { public abstract class ApiViewComponentBase : ViewComponent { private readonly HttpClient _httpClient; private readonly TelemetryClient _telemetry; protected ApiViewComponentBase(IHttpClientFactory httpClientFactory, TelemetryClient telemetry) { _httpClient = httpClientFactory.CreateClient("ApiClient"); _telemetry = telemetry; } /// /// Fetches data from API as JObject /// /// API endpoint path (e.g. "/api/product/get/1") /// JObject with API result protected async Task GetJObjectFromApiAsync(string apiEndpoint) { try { _telemetry.TrackEvent("ApiCall", new Dictionary { ["Endpoint"] = apiEndpoint, ["Source"] = "GetJObjectFromApiAsync" }); // Use HttpClient to get JSON string var response = await _httpClient.GetAsync(apiEndpoint); response.EnsureSuccessStatusCode(); var jsonString = await response.Content.ReadAsStringAsync(); return JObject.Parse(jsonString); } catch (Exception ex) { _telemetry.TrackException(ex, new Dictionary { ["Endpoint"] = apiEndpoint, ["Method"] = "GetJObjectFromApiAsync" }); return null; } } /// /// Fetches data from API as JArray /// /// API endpoint path /// JArray with API result protected async Task GetJArrayFromApiAsync(string apiEndpoint) { try { _telemetry.TrackEvent("ApiCall", new Dictionary { ["Endpoint"] = apiEndpoint, ["Source"] = "GetJArrayFromApiAsync" }); // Use HttpClient to get JSON string var response = await _httpClient.GetAsync(apiEndpoint); response.EnsureSuccessStatusCode(); var jsonString = await response.Content.ReadAsStringAsync(); return JArray.Parse(jsonString); } catch (Exception ex) { _telemetry.TrackException(ex, new Dictionary { ["Endpoint"] = apiEndpoint, ["Method"] = "GetJArrayFromApiAsync" }); return null; } } /// /// Sends POST request to API and receives JObject response /// /// API endpoint path /// Data to be sent (can be JObject or other type) /// JObject with response data protected async Task PostToApiAsync(string apiEndpoint, object data) { try { _telemetry.TrackEvent("ApiPost", new Dictionary { ["Endpoint"] = apiEndpoint }); // Convert data to JSON string var content = new StringContent( JsonConvert.SerializeObject(data), System.Text.Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(apiEndpoint, content); response.EnsureSuccessStatusCode(); var jsonString = await response.Content.ReadAsStringAsync(); return JObject.Parse(jsonString); } catch (Exception ex) { _telemetry.TrackException(ex, new Dictionary { ["Endpoint"] = apiEndpoint, ["Method"] = "PostToApiAsync" }); return null; } } /// /// Handles errors in a consistent way /// protected IViewComponentResult HandleError(string message = "An error occurred.") { _telemetry.TrackEvent("ComponentError", new Dictionary { ["Message"] = message, ["Component"] = this.GetType().Name }); return Content(message); } } }