Skip to content

Commit

Permalink
export via api
Browse files Browse the repository at this point in the history
  • Loading branch information
Eliran-Turgeman committed Dec 6, 2024
1 parent 67be6a8 commit 32a43c0
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions EmailCollector.Api/Controllers/SignupFormsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using EmailCollector.Api.DTOs;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using EmailCollector.Api.Services;
using EmailCollector.Api.Services.Exports;

namespace EmailCollector.Api.Controllers;

Expand Down Expand Up @@ -215,4 +216,42 @@ public async Task<IActionResult> PutSignupForm(int id, CreateFormDto signupForm)

return NoContent();
}

/// <summary>
/// Export all forms for the current user to desired format.
/// Supporting CSV and JSON formats.
/// </summary>
/// <returns></returns>
[HttpPost("export")]
[ServiceFilter(typeof(ApiKeyAuthFilter))]
public async Task<IActionResult> ExportForms([FromBody] ExportFormat? exportFormat)
{
_logger.LogInformation($"Exporting forms.");
var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (string.IsNullOrEmpty(userIdClaim) || !Guid.TryParse(userIdClaim, out var userId))
{
return Unauthorized("Invalid or missing user identifier");
}
var forms = await _formService.GetFormsByUserAsync(userId);
var formIds = forms.Select(f => f.Id).ToList();

var format = exportFormat ?? ExportFormat.Csv;

var fileBytes = await _formService.ExportFormsAsync(formIds, format);
if (fileBytes == null || fileBytes.Length == 0)
{
_logger.LogInformation("No forms were available for export or result was empty.");
return NotFound("No forms found to export.");
}

string contentType = "application/octet-stream";
string fileName = exportFormat switch
{
ExportFormat.Csv => "collecto_export.csv",
ExportFormat.Json => "collecto_export.xlsx",
_ => "collecto_export.txt",
};

return File(fileBytes, contentType, fileName);
}
}

0 comments on commit 32a43c0

Please sign in to comment.