C
C#2y ago
barcode

✅ validation question

Should I be checking if a entity for a given id exists in my validator or should this be done in the requesthandler of mediator? I'm using fluent validation ex:
public CreateReviewCommandValidator()
{
RuleFor(x => x.CenterId)
.NotEmpty().WithMessage("{PropertyName} must be provided.")
.MustAsync(CenterExist).WithMessage("Center with that id doesn't exist.");

}

private async Task<bool> CenterExist(int centerId, CancellationToken cancellationToken)
{
return await _dbContext.Centers
.AnyAsync(x => x.Id == centerId, cancellationToken: cancellationToken);
}
public CreateReviewCommandValidator()
{
RuleFor(x => x.CenterId)
.NotEmpty().WithMessage("{PropertyName} must be provided.")
.MustAsync(CenterExist).WithMessage("Center with that id doesn't exist.");

}

private async Task<bool> CenterExist(int centerId, CancellationToken cancellationToken)
{
return await _dbContext.Centers
.AnyAsync(x => x.Id == centerId, cancellationToken: cancellationToken);
}
3 Replies
Angius
Angius2y ago
The request with an ID that doesn't exist isn't invalid, if you ask me It should probably be handled wherever you query the database For example throw a custom NotFoundException and catch it with the exception handling middleware Or just return NotFound() straight if you can
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
barcode
barcodeOP2y ago
got it ty
Want results from more Discord servers?
Add your server