using FastEndpoints;
using FluentValidation.Results;
using GB5Shared.DTO.ReportOrchestration;
using Microsoft.AspNetCore.Http;
namespace FrameworkSL.ReportOrchestration
{
///
/// Extension methods to convert a ReportExecutionResult into an appropriate
/// HTTP response from a FastEndpoints endpoint.
/// Call from ExecuteAsync: await result.SendResponseAsync(HttpContext, ct);
///
public static class ReportResultExtensions
{
public static async Task SendResponseAsync(
this ReportExecutionResult result,
HttpContext httpContext,
CancellationToken ct = default)
{
switch (result.ResultType)
{
case ReportResultType.SyncCompleted when result.ExportStream is not null:
result.ExportStream.Seek(0, SeekOrigin.Begin);
await httpContext.Response
.SendStreamAsync(
result.ExportStream,
result.ContentType ?? "application/octet-stream",
result.ExportStream.Length,
result.FileName,
cancellation: ct)
.ConfigureAwait(false);
break;
case ReportResultType.SyncCompleted:
await httpContext.Response
.SendOkAsync(new
{
Data = result.GridData,
TotalRows = result.TotalRows,
IsFromCache = result.IsFromCache,
DataSource = result.DataSourceUsed.ToString(),
CorrelationId = result.CorrelationId,
ElapsedMs = (long)result.ElapsedTime.TotalMilliseconds
}, cancellation: ct)
.ConfigureAwait(false);
break;
case ReportResultType.AsyncSubmitted:
await httpContext.Response
.SendOkAsync(new
{
SysJobId = result.SysJobId,
Message = result.AsyncMessage,
CorrelationId = result.CorrelationId,
ElapsedMs = (long)result.ElapsedTime.TotalMilliseconds
}, cancellation: ct)
.ConfigureAwait(false);
break;
case ReportResultType.Failed:
default:
await httpContext.Response
.SendErrorsAsync(
new List
{
new(string.Empty,
result.ErrorMessage ?? "An unexpected error occurred.")
},
statusCode: 500,
cancellation: ct)
.ConfigureAwait(false);
break;
}
}
}
}