MrDave1999 / SimpleResults

A simple library to implement the Result pattern for returning from services
https://mrdave1999.github.io/SimpleResults
MIT License
103 stars 2 forks source link

Add a result operation to represent the file contents #59

Closed MrDave1999 closed 6 months ago

MrDave1999 commented 6 months ago

New types to be added:

public class StreamFileContent
{
    public StreamFileContent(Stream content) => Content = content;
    public Stream Content { get; }
    public string ContentType { get; init; } = string.Empty;
    public string FileName { get; init; } = string.Empty;
}

public class ByteArrayFileContent
{
    public ByteArrayFileContent(byte[] content) => Content = content;
    public byte[] Content { get; }
    public string ContentType { get; init; } = string.Empty;
    public string FileName { get; init; } = string.Empty;
}

These types represent the content of a file.

Two methods are added to the Result type:

public static Result<StreamFileContent> File(StreamFileContent fileContent);
public static Result<ByteArrayFileContent> File(ByteArrayFileContent fileContent);

Usage

public class DownloadProformaInvoiceUseCase(
    IHtmlTemplateLoader htmlTemplateLoader,
    IHtmlConverter htmlConverter,
    DownloadProformaInvoiceValidator validator)
{
    public async Task<Result<ByteArrayFileContent>> DownloadAsPdfAsync(DownloadProformaInvoiceRequest request)
    {
        ValidationResult result = validator.Validate(request);
        if (result.IsFailed())
            return Result.Invalid(result.AsErrors());

        var html = await htmlTemplateLoader
            .LoadAsync("./Templates/ProformaInvoice.html", request.MapToObject());

        byte[] fileContents = htmlConverter.ConvertToPdf(html, new MemoryStream());
        var byteArrayFileContent = new ByteArrayFileContent(fileContents)
        {
            ContentType = "application/pdf",
            FileName = "Report.pdf"
        };
        return Result.File(byteArrayFileContent);
    }
}

If the result is successful, Result<ByteArrayFileContent> should be translated to an object like FileContentResult or FileStreamResult (these are types used in MVC controllers).

Support should also be added for Minimal APIs. See, FileContentHttpResult and FileStreamHttpResult.