Handler.cs 1.5 KB

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