Handler.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Microsoft.EntityFrameworkCore;
  4. using SharedKernel.Results;
  5. namespace Application.Features.Api.Stocks.GetDetail;
  6. internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
  7. {
  8. private const int RecentPriceCount = 30;
  9. public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
  10. {
  11. var stock = await db.Stock.AsNoTracking().FirstOrDefaultAsync(c => c.Code == request.Code, ct);
  12. if (stock is null)
  13. {
  14. return Result.Failure<Response>(Error.NotFound("Stock.NotFound", "종목을 찾을 수 없습니다."));
  15. }
  16. var prices = await db.StockDailyPrice.AsNoTracking()
  17. .Where(c => c.StockID == stock.ID)
  18. .OrderByDescending(c => c.TradingDate)
  19. .Take(RecentPriceCount)
  20. .Select(c => new Response.PriceRow
  21. {
  22. TradingDate = c.TradingDate,
  23. Open = c.Open,
  24. High = c.High,
  25. Low = c.Low,
  26. Close = c.Close,
  27. Volume = c.Volume,
  28. TradingValue = c.TradingValue,
  29. ChangeAmount = c.ChangeAmount,
  30. ChangeRate = c.ChangeRate
  31. })
  32. .ToListAsync(ct);
  33. return new Response
  34. {
  35. Code = stock.Code,
  36. ISIN = stock.ISIN,
  37. Name = stock.Name,
  38. EnglishName = stock.EnglishName,
  39. Market = stock.Market.ToString(),
  40. TradingStatus = stock.TradingStatus.ToString(),
  41. SectorName = stock.SectorName,
  42. IsActive = stock.IsActive,
  43. ListedDate = stock.ListedDate,
  44. DelistedDate = stock.DelistedDate,
  45. LastTradingDate = stock.LastTradingDate,
  46. ClosePrice = stock.LastClosePrice,
  47. ChangeRate = stock.LastChangeRate,
  48. MarketCap = stock.MarketCap,
  49. RecentPrices = prices
  50. };
  51. }
  52. }