diff --git a/FileStorage/Controllers/FileController.cs b/FileStorage/Controllers/FileController.cs index 074924a..f2529c2 100644 --- a/FileStorage/Controllers/FileController.cs +++ b/FileStorage/Controllers/FileController.cs @@ -137,6 +137,42 @@ public async Task GetDocumentByHash(string hash) }; } + [HttpDelete("{id}")] + public async Task DeleteDocument(Guid id) + { + var document = await _context.Documents.FindAsync(id); + if (document == null) + return NotFound("Document not found."); + + // Try to delete the file from disk if present + try + { + if (System.IO.File.Exists(document.FilePath)) + { + System.IO.File.Delete(document.FilePath); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error deleting file: {ex.Message}"); + return StatusCode(500, "Error deleting file from disk."); + } + + // Remove database entry + _context.Documents.Remove(document); + try + { + await _context.SaveChangesAsync(); + } + catch (Exception ex) + { + Console.WriteLine($"Error deleting document from database: {ex.Message}"); + return StatusCode(500, "Error deleting document from database."); + } + + return Ok(); + } + private string GetMimeType(string filePath) { var provider = new FileExtensionContentTypeProvider(); diff --git a/FileStorageTest/UnitTest1.cs b/FileStorageTest/UnitTest1.cs index a70bb61..fdc5c06 100644 --- a/FileStorageTest/UnitTest1.cs +++ b/FileStorageTest/UnitTest1.cs @@ -146,5 +146,39 @@ public async Task GetDocumentByHash_ExistingHash_ReturnsFileStreamResult() Assert.That(result, Is.TypeOf()); } + + [Test] + public async Task DeleteDocument_NonExistentId_ReturnsNotFound() + { + var result = await _controller.DeleteDocument(Guid.NewGuid()); + + Assert.That(result, Is.TypeOf()); + } + + [Test] + public async Task DeleteDocument_ExistingId_RemovesFileAndEntry() + { + var documentId = Guid.NewGuid(); + var document = new File + { + Id = documentId, + Name = "test.txt", + FilePath = Path.Combine(_rootPath, "test.txt"), + Hash = "hash", + UploadedAt = DateTime.UtcNow + }; + _context.Documents.Add(document); + await _context.SaveChangesAsync(); + + // Create the file + _testFilePath = document.FilePath; + await System.IO.File.WriteAllTextAsync(_testFilePath, "content"); + + var result = await _controller.DeleteDocument(documentId); + + Assert.That(result, Is.TypeOf()); + Assert.That(await _context.Documents.FindAsync(documentId), Is.Null); + Assert.That(System.IO.File.Exists(_testFilePath), Is.False); + } } } \ No newline at end of file