using Application.Abstractions.Messaging; using Application.Abstractions.Cache; using Application.Abstractions.Crypto; namespace Application.Features.Api.Crypto.Candle.GetMinutes; public sealed class Handler(IUpbitClient upbit, ICacheService cache) : IQueryHandler { private static readonly int[] _allowedUnits = [1, 3, 5, 10, 15, 30, 60, 240]; private static readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(5); public async Task Handle(Query request, CancellationToken ct) { if (!_allowedUnits.Contains(request.Unit)) { return new Response([]); } var count = Math.Clamp(request.Count, 1, 200); var cacheKey = CacheKeys.CryptoCandle(request.Market, $"m{request.Unit}"); // 캐시 확인 var cached = await cache.GetAsync>(cacheKey, ct); if (cached is { Count: > 0 }) { return new Response(cached); } // Upbit REST API 호출 var candles = await upbit.GetMinuteCandlesAsync(request.Market, request.Unit, count, ct); var items = candles .OrderBy(c => c.CandleDateTimeUtc) .Select(c => new Response.CandleItem( c.CandleDateTimeUtc, c.CandleDateTimeKst, c.OpeningPrice, c.HighPrice, c.LowPrice, c.TradePrice, c.Timestamp, c.CandleAccTradePrice, c.CandleAccTradeVolume, c.Unit ?? request.Unit )) .ToList(); // Redis 캐시 저장 (5분) if (items.Count > 0) { await cache.SetAsync(cacheKey, items, _cacheExpiry, ct); } return new Response(items); } }