Add more logging and trace parameters
This commit is contained in:
@@ -39,19 +39,41 @@ public static class CreateCar
|
||||
IEnumerable<IValidator<Request>> validators,
|
||||
ApplicationDbContext dbContext,
|
||||
UserAccessor userAccessor,
|
||||
ILoggerFactory loggerFactory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ILogger logger = loggerFactory.CreateLogger(nameof(CreateCar));
|
||||
|
||||
List<ValidationResult> failedValidations = await validators.ValidateAllAsync(request, cancellationToken: cancellationToken);
|
||||
if (failedValidations.Count > 0)
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Validation failed for request {@Request} with errors {@Errors}",
|
||||
request,
|
||||
failedValidations
|
||||
.Where(x => !x.IsValid)
|
||||
.SelectMany(x => x.Errors)
|
||||
.Select(x => x.ErrorMessage));
|
||||
|
||||
return TypedResults.BadRequest(new HttpValidationProblemDetails(failedValidations.ToCombinedDictionary()));
|
||||
}
|
||||
|
||||
bool isDuplicate = await dbContext.Cars
|
||||
.AnyAsync(x => x.Name.ToUpper() == request.Name.ToUpper(), cancellationToken);
|
||||
|
||||
if (isDuplicate)
|
||||
{
|
||||
logger.LogDebug("Car with name '{CarName}' (case insensitive) already exists", request.Name);
|
||||
return TypedResults.Conflict();
|
||||
}
|
||||
|
||||
string userId = userAccessor.GetUserId();
|
||||
|
||||
User? user = await dbContext.Users.FindAsync([userId], cancellationToken: cancellationToken);
|
||||
if (user is null)
|
||||
{
|
||||
logger.LogDebug("User with ID '{UserId}' not found, creating new user", userId);
|
||||
|
||||
user = new User
|
||||
{
|
||||
Id = userId
|
||||
@@ -65,17 +87,11 @@ public static class CreateCar
|
||||
UserId = userId
|
||||
};
|
||||
|
||||
bool isDuplicate = await dbContext.Cars
|
||||
.AnyAsync(x => x.Name.ToUpper() == request.Name.ToUpper(), cancellationToken);
|
||||
|
||||
if (isDuplicate)
|
||||
{
|
||||
return TypedResults.Conflict();
|
||||
}
|
||||
|
||||
await dbContext.Cars.AddAsync(car, cancellationToken);
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
logger.LogTrace("Created new car: {@Car}", car);
|
||||
|
||||
Response response = new(car.Id.Value, car.Name);
|
||||
return TypedResults.Created($"/v1/cars/{car.Id}", response);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user