fix(api): validate block group exists on block creation
POST /api/blocks with a nonexistent blockGroupId returned an unhandled DbUpdateException (HTTP 500) because CreateBlockHandler never checked the referenced block group before inserting, letting the SQLite FK constraint raise. Add a BaseError validation (422), matching the "does not exist" precedent already used elsewhere. Found via live E2E testing.
This commit is contained in:
@@ -25,13 +25,29 @@ public class CreateBlockHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
return Mapper.ProjectToViewModel(block);
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request) =>
|
||||
await ValidateBlockName(dbContext, request).MapT(name => new Block
|
||||
private static async Task<Validation<BaseError, Block>> Validate(TvContext dbContext, CreateBlock request)
|
||||
{
|
||||
Validation<BaseError, Unit> blockGroupValidation = await ValidateBlockGroupExists(dbContext, request);
|
||||
Validation<BaseError, string> nameValidation = await ValidateBlockName(dbContext, request);
|
||||
|
||||
return (blockGroupValidation, nameValidation).Apply((_, name) => new Block
|
||||
{
|
||||
BlockGroupId = request.BlockGroupId,
|
||||
Name = name,
|
||||
Minutes = 30
|
||||
});
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, Unit>> ValidateBlockGroupExists(
|
||||
TvContext dbContext,
|
||||
CreateBlock request)
|
||||
{
|
||||
bool blockGroupExists = await dbContext.BlockGroups.AnyAsync(bg => bg.Id == request.BlockGroupId);
|
||||
|
||||
return blockGroupExists
|
||||
? Success<BaseError, Unit>(Unit.Default)
|
||||
: BaseError.New("Block group does not exist");
|
||||
}
|
||||
|
||||
private static async Task<Validation<BaseError, string>> ValidateBlockName(
|
||||
TvContext dbContext,
|
||||
|
||||
Reference in New Issue
Block a user