using System.Text.Json; using Microsoft.Extensions.Caching.Memory; namespace economy.Models.Price.Global { public class GlobalModel { private readonly Alpha_API _alphaAPI; private readonly IMemoryCache _cache; public GlobalModel(Alpha_API alphaAPI, IMemoryCache cache) { _alphaAPI = alphaAPI; _cache = cache; } // 천연가스 시세 조회 public async Task GetNaturalGasPriceInfo(NaturalGas.Request request) { string cacheKey = $"Alpha_NATURAL_GAS_{request.Interval}"; // 캐시에 데이터가 존재하면 반환 if (_cache.TryGetValue(cacheKey, out NaturalGas.Response cachedData)) { return cachedData; } NaturalGas.Response parseData = new(); try { var uriBuilder = new UriBuilder(_alphaAPI.APIUrl) { Path = "/query", Query = $"function=NATURAL_GAS&interval={request.Interval}&apikey={_alphaAPI.APIKey}" }; var response = await _alphaAPI.httpClient.GetAsync(uriBuilder.Uri); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); parseData = JsonSerializer.Deserialize(jsonString); // 호출 한도 초과 시 HTTP 200 + Information 응답이 와서 Data가 null이 됨 — 빈 응답은 캐시하지 않음 if (parseData.Data is null) { return new NaturalGas.Response(); } // 캐시에 저장 (1일 동안 유지) _cache.Set(cacheKey, parseData, TimeSpan.FromDays(1)); } response.EnsureSuccessStatusCode(); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } return parseData; } // 국제 원자재 시세 조회 (구리, 알루미늄, 밀, 섬유(면화), 설탕, 커피, 원자재 종합지수) public async Task GetCommodityPriceInfo(string function, string interval) { string cacheKey = $"Alpha_{function}_{interval}"; // 캐시에 데이터가 존재하면 반환 if (_cache.TryGetValue(cacheKey, out Commodity.Response cachedData)) { return cachedData; } Commodity.Response parseData = new(); try { var uriBuilder = new UriBuilder(_alphaAPI.APIUrl) { Path = "/query", Query = $"function={function}&interval={interval}&apikey={_alphaAPI.APIKey}" }; var response = await _alphaAPI.httpClient.GetAsync(uriBuilder.Uri); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); parseData = JsonSerializer.Deserialize(jsonString); // 호출 한도 초과 시 HTTP 200 + Information 응답이 와서 Data가 null이 됨 — 빈 응답은 캐시하지 않음 if (parseData.Data is null) { return new Commodity.Response(); } // 캐시에 저장 (1일 동안 유지) _cache.Set(cacheKey, parseData, TimeSpan.FromDays(1)); } response.EnsureSuccessStatusCode(); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } return parseData; } } }