using System.Text.Json;
using Microsoft.Extensions.Logging;
using StellaOps.Microservice;
namespace Examples.Billing.Microservice.Endpoints;
///
/// Endpoint for uploading attachments to an invoice.
/// Demonstrates streaming upload using IRawStellaEndpoint.
///
[StellaEndpoint("POST", "/invoices/{id}/attachments", SupportsStreaming = true, TimeoutSeconds = 300)]
public sealed class UploadAttachmentEndpoint : IRawStellaEndpoint
{
private readonly ILogger _logger;
public UploadAttachmentEndpoint(ILogger logger)
{
_logger = logger;
}
public async Task HandleAsync(
RawRequestContext context,
CancellationToken cancellationToken)
{
var invoiceId = context.PathParameters.GetValueOrDefault("id") ?? "unknown";
var contentType = context.Headers["Content-Type"] ?? "application/octet-stream";
_logger.LogInformation(
"Uploading attachment for invoice {InvoiceId}, Content-Type: {ContentType}",
invoiceId,
contentType);
// Read the streamed body
long totalBytes = 0;
var buffer = new byte[8192];
int bytesRead;
while ((bytesRead = await context.Body.ReadAsync(buffer, cancellationToken)) > 0)
{
totalBytes += bytesRead;
// In a real implementation, you would write to storage here
}
_logger.LogInformation(
"Received {TotalBytes} bytes for invoice {InvoiceId}",
totalBytes,
invoiceId);
// Return success response
var response = new
{
invoiceId,
attachmentId = $"ATT-{Guid.NewGuid():N}"[..16].ToUpperInvariant(),
size = totalBytes,
uploadedAt = DateTime.UtcNow
};
return RawResponse.Ok(JsonSerializer.Serialize(response));
}
}