Changed InvokeRecActionCommand and its handler to return a boolean indicating success or failure, allowing consumers to check if the action was successful. This improves clarity and error handling in command execution.
70 lines
2.2 KiB
C#
70 lines
2.2 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<bool>
|
|
{
|
|
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, bool>
|
|
{
|
|
public async Task<bool> 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();
|
|
|
|
var statusCode = (short)response.StatusCode;
|
|
|
|
await sender.Send(new CreateOutResCommand
|
|
{
|
|
Status = statusCode,
|
|
ActionId = action.Id,
|
|
Header = JsonSerializer.Serialize(resHeaders, options: new() { WriteIndented = false }),
|
|
Body = resBody,
|
|
AddedWho = config?["AddedWho"]
|
|
}, cancel);
|
|
|
|
return response.IsSuccessStatusCode;
|
|
}
|
|
} |