Cleaned up unused namespaces to improve code maintainability: - Removed `System.Text.Json` from `CreateOutResCommand.cs`. - Removed `Microsoft.Extensions.Logging` from `InvokeRecActionCommand.cs`. This reduces unnecessary dependencies and improves readability.
65 lines
2.1 KiB
C#
65 lines
2.1 KiB
C#
using MediatR;
|
|
using Microsoft.Extensions.Configuration;
|
|
using ReC.Application.Common;
|
|
using ReC.Application.Common.Dto;
|
|
using ReC.Application.Common.Exceptions;
|
|
using ReC.Application.OutResults.Commands;
|
|
using System.Text.Json;
|
|
|
|
namespace ReC.Application.RecActions.Commands;
|
|
|
|
public record InvokeRecActionCommand : IRequest
|
|
{
|
|
public RecActionDto Action { get; set; } = null!;
|
|
}
|
|
|
|
public static class InvokeRecActionCommandExtensions
|
|
{
|
|
public static InvokeRecActionCommand ToInvokeCommand(this RecActionDto dto) => new() { Action = dto };
|
|
}
|
|
|
|
public class InvokeRecActionCommandHandler(
|
|
ISender sender,
|
|
IHttpClientFactory clientFactory,
|
|
IConfiguration? config = null
|
|
) : IRequestHandler<InvokeRecActionCommand>
|
|
{
|
|
public async Task Handle(InvokeRecActionCommand request, CancellationToken cancel)
|
|
{
|
|
var action = request.Action;
|
|
using var http = clientFactory.CreateClient();
|
|
|
|
if (action.RestType is null)
|
|
throw new DataIntegrityException(
|
|
$"Rec action could not be invoked because the RestType value is null. " +
|
|
$"ProfileId: {action.ProfileId}, " +
|
|
$"Id: {action.Id}"
|
|
);
|
|
|
|
using var httpReq = action.RestType
|
|
.ToHttpMethod()
|
|
.ToHttpRequestMessage(action.EndpointUri);
|
|
|
|
if(action.Body is not null)
|
|
{
|
|
using var reqBody = new StringContent(action.Body);
|
|
httpReq.Content = reqBody;
|
|
}
|
|
|
|
if (action.Headers is not null)
|
|
foreach (var header in action.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 = action.Id,
|
|
Header = JsonSerializer.Serialize(resHeaders, options: new() { WriteIndented = false }),
|
|
Body = resBody,
|
|
AddedWho = config?["AddedWho"]
|
|
}, cancel);
|
|
}
|
|
} |