Handler.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 cacheKey = CacheKeys.CryptoCandle(request.Market, $"m{request.Unit}");
  17. // 캐시 확인
  18. var cached = await cache.GetAsync<List<Response.CandleItem>>(cacheKey, ct);
  19. if (cached is { Count: > 0 })
  20. {
  21. return new Response(cached);
  22. }
  23. // Upbit REST API 호출
  24. var candles = await upbit.GetMinuteCandlesAsync(request.Market, request.Unit, count, ct);
  25. var items = candles
  26. .OrderBy(c => c.CandleDateTimeUtc)
  27. .Select(c => new Response.CandleItem(
  28. c.CandleDateTimeUtc,
  29. c.CandleDateTimeKst,
  30. c.OpeningPrice,
  31. c.HighPrice,
  32. c.LowPrice,
  33. c.TradePrice,
  34. c.Timestamp,
  35. c.CandleAccTradePrice,
  36. c.CandleAccTradeVolume,
  37. c.Unit ?? request.Unit
  38. ))
  39. .ToList();
  40. // Redis 캐시 저장 (5분)
  41. if (items.Count > 0)
  42. {
  43. await cache.SetAsync(cacheKey, items, _cacheExpiry, ct);
  44. }
  45. return new Response(items);
  46. }
  47. }