Handler.cs 1.6 KB

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