Skip to content

Commit

Permalink
feat: implement delete file
Browse files Browse the repository at this point in the history
  • Loading branch information
HunorTotBagi committed Jan 4, 2025
1 parent 7885103 commit 64c274b
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Files.Application.Entities.Files.Commands.DeleteFileAsset;

namespace Files.Api.Endpoints.Files;

public class DeleteFileAsset : ICarterModule
{
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapDelete("/Files/{fileId}", async (string fileId, ISender sender) =>
{
var result = await sender.Send(new DeleteFileAssetCommand(fileId));
var response = result.Adapt<DeleteFileAssetResponse>();

return Results.Ok(response);
})
.WithName("DeleteFileAsset")
.Produces<DeleteFileAssetResponse>()
.ProducesProblem(StatusCodes.Status400BadRequest)
.ProducesProblem(StatusCodes.Status404NotFound)
.WithSummary("Delete File Asset")
.WithDescription("Delete File Asset");
}
}

public record DeleteFileAssetResponse(bool IsSuccess);
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Files.Application.Entities.Files.Commands.DeleteFileAsset;

public record DeleteFileAssetCommand(string FileAssetId) : ICommand<DeleteFileAssetResult>;

public record DeleteFileAssetResult(bool IsSuccess);

public class DeleteFileAssetCommandValidator : AbstractValidator<DeleteFileAssetCommand>
{
public DeleteFileAssetCommandValidator()
{
RuleFor(x => x.FileAssetId).NotEmpty().WithMessage("FileAssetId is required");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using Files.Application.Entities.Files.Exceptions;

namespace Files.Application.Entities.Files.Commands.DeleteFileAsset;

public class DeleteFileAssetHandler(IFilesDbContext dbContext) : ICommandHandler<DeleteFileAssetCommand, DeleteFileAssetResult>
{
public async Task<DeleteFileAssetResult> Handle(DeleteFileAssetCommand command, CancellationToken cancellationToken)
{
var fileAsset = await dbContext.FileAssets
.AsNoTracking()
.SingleOrDefaultAsync(f => f.Id == FileAssetId.Of(Guid.Parse(command.FileAssetId)), cancellationToken);

if (fileAsset is null)
throw new FileAssetNotFoundException(command.FileAssetId);


dbContext.FileAssets.Remove(fileAsset);
await dbContext.SaveChangesAsync(cancellationToken);

return new DeleteFileAssetResult(true);
}
}

0 comments on commit 64c274b

Please sign in to comment.