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 market = $"KRW-{request.Symbol.ToUpper()}"; var cacheKey = CacheKeys.CryptoCandle(request.Symbol, $"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(market, request.Unit, count, ct); var items = candles .OrderBy(c => c.CandleDateTimeUtc) .Select(c => new Response.CandleItem( new DateTimeOffset(c.CandleDateTimeUtc, TimeSpan.Zero).ToUnixTimeSeconds(), c.OpeningPrice, c.HighPrice, c.LowPrice, c.TradePrice, c.CandleAccTradeVolume, c.CandleAccTradePrice )) .ToList(); // Redis 캐시 저장 (5분) if (items.Count > 0) { await cache.SetAsync(cacheKey, items, _cacheExpiry, ct); } return new Response(items); } }