using Application.Abstractions.YouTube; using Microsoft.Extensions.Logging; namespace Infrastructure.YouTube; /// /// YouTube Data API v3 요청에 API Key를 자동으로 추가하는 DelegatingHandler. /// 실제 캐시/조회는 싱글톤에 위임. /// internal sealed class YouTubeApiKeyHandler( IYouTubeApiKeyProvider keyProvider, ILogger logger ) : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var apiKey = await keyProvider.GetAsync(cancellationToken); if (!string.IsNullOrEmpty(apiKey) && request.RequestUri is not null) { // 이미 Authorization 헤더(OAuth)가 있으면 API Key 추가 안 함 if (request.Headers.Authorization is null) { var uriStr = request.RequestUri.ToString(); var separator = uriStr.Contains('?') ? "&" : "?"; request.RequestUri = new Uri($"{uriStr}{separator}key={Uri.EscapeDataString(apiKey)}"); } } else { logger.LogWarning("[YouTube] API Key가 비어있습니다. DB Config > External > YouTubeApiKeyEnc를 확인하세요."); } return await base.SendAsync(request, cancellationToken); } }