Fixing 500 error when entering a bad itemid when creating an auction

This commit is contained in:
hz
2025-06-05 09:44:04 -05:00
parent ea25e3b63d
commit a88e50d111
3 changed files with 42 additions and 2 deletions
@@ -0,0 +1,32 @@
using GameAuthApi.Services;
using Microsoft.Extensions.Configuration;
public class ServiceValidationTests
{
private static IConfiguration cfg = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string,string>
{
{"MongoDB:ConnectionString","mongodb://localhost"},
{"MongoDB:DatabaseName","test"}
}).Build();
[Fact]
public async Task ItemService_InvalidId_ReturnsNull()
{
var svc = new ItemService(cfg);
var result = await svc.GetByIdAsync("bad");
Assert.Null(result);
}
[Fact]
public async Task AuctionService_InvalidId_ReturnsNull()
{
var svc = new AuctionService(cfg);
var result = await svc.GetByIdAsync("bad");
Assert.Null(result);
}
}
+7 -2
View File
@@ -20,8 +20,13 @@ public class AuctionService
public virtual async Task CreateAsync(Auction auction) =>
await _auctions.InsertOneAsync(auction);
public virtual async Task<Auction> GetByIdAsync(string id) =>
await _auctions.Find(a => a.Id == id).FirstOrDefaultAsync();
public virtual async Task<Auction> GetByIdAsync(string id)
{
if (!MongoDB.Bson.ObjectId.TryParse(id, out _))
return null;
return await _auctions.Find(a => a.Id == id).FirstOrDefaultAsync();
}
public virtual async Task UpdateAsync(Auction auction) =>
await _auctions.ReplaceOneAsync(a => a.Id == auction.Id, auction);
+3
View File
@@ -29,6 +29,9 @@ public class ItemService
public virtual async Task<Item> GetByIdAsync(string id)
{
if (!MongoDB.Bson.ObjectId.TryParse(id, out _))
return null;
return await _items.Find(i => i.Id == id).FirstOrDefaultAsync();
}