Handler.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Cache;
  3. using Application.Abstractions.Crypto;
  4. namespace Application.Features.Api.Crypto.Candle.GetMinutes;
  5. public sealed class Handler(IUpbitClient upbit, ICacheService cache) : IQueryHandler<Query, Response>
  6. {
  7. private static readonly int[] _allowedUnits = [1, 3, 5, 10, 15, 30, 60, 240];
  8. private static readonly TimeSpan _cacheExpiry = TimeSpan.FromMinutes(5);
  9. public async Task<Response> Handle(Query request, CancellationToken ct)
  10. {
  11. if (!_allowedUnits.Contains(request.Unit))
  12. {
  13. return new Response([]);
  14. }
  15. var count = Math.Clamp(request.Count, 1, 200);
  16. var market = $"KRW-{request.Symbol.ToUpper()}";
  17. var cacheKey = CacheKeys.CryptoCandle(request.Symbol, $"m{request.Unit}");
  18. // 캐시 확인
  19. var cached = await cache.GetAsync<List<Response.CandleItem>>(cacheKey, ct);
  20. if (cached is { Count: > 0 })
  21. {
  22. return new Response(cached);
  23. }
  24. // Upbit REST API 호출
  25. var candles = await upbit.GetMinuteCandlesAsync(market, request.Unit, count, ct);
  26. var items = candles
  27. .OrderBy(c => c.CandleDateTimeUtc)
  28. .Select(c => new Response.CandleItem(
  29. new DateTimeOffset(c.CandleDateTimeUtc, TimeSpan.Zero).ToUnixTimeSeconds(),
  30. c.OpeningPrice,
  31. c.HighPrice,
  32. c.LowPrice,
  33. c.TradePrice,
  34. c.CandleAccTradeVolume,
  35. c.CandleAccTradePrice
  36. ))
  37. .ToList();
  38. // Redis 캐시 저장 (5분)
  39. if (items.Count > 0)
  40. {
  41. await cache.SetAsync(cacheKey, items, _cacheExpiry, ct);
  42. }
  43. return new Response(items);
  44. }
  45. }