using MediatR; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using ReC.Application.Common; using ReC.Application.Common.Dto; using ReC.Application.OutResults.Commands; using System.Text.Json; namespace ReC.Application.RecActions.Commands; public record InvokeRecActionCommand : RecActionDto, IRequest { public InvokeRecActionCommand(RecActionDto root) : base(root) { } public InvokeRecActionCommand() { } } public static class InvokeRecActionCommandExtensions { public static InvokeRecActionCommand ToInvokeCommand(this RecActionDto dto) => new(dto); } public class InvokeRecActionCommandHandler( ISender sender, IHttpClientFactory clientFactory, IConfiguration? config = null, ILogger? logger = null ) : IRequestHandler { public async Task Handle(InvokeRecActionCommand request, CancellationToken cancel) { using var http = clientFactory.CreateClient(); if (request.RestType is null) { logger?.LogWarning( "Rec action could not be invoked because the RestType value is null. ProfileId: {ProfileId}, ActionId: {ActionId}", request.ProfileId, request.ActionId ); return; } using var httpReq = request.RestType .ToHttpMethod() .ToHttpRequestMessage(request.EndpointUri); if(request.Body is not null) { using var reqBody = new StringContent(request.Body); httpReq.Content = reqBody; } if (request.Headers is not null) foreach (var header in request.Headers) httpReq.Headers.Add(header.Key, header.Value); using var response = await http.SendAsync(httpReq, cancel); var resBody = await response.Content.ReadAsStringAsync(cancel); var resHeaders = response.Headers.ToDictionary(); await sender.Send(new CreateOutResCommand { ActionId = request.ActionId, Header = JsonSerializer.Serialize(resHeaders, options: new() { WriteIndented = false }), Body = resBody, AddedWho = config?["AddedWho"] }, cancel); } }