mirror of
https://github.com/aaronpo97/the-biergarten-app.git
synced 2026-10-14 17:54:42 +00:00
formatting
This commit is contained in:
@@ -1020,9 +1020,7 @@ public class AuthSteps(ScenarioContext scenario)
|
||||
public async Task WhenISubmitAResendConfirmationRequestWithoutAnAccessToken()
|
||||
{
|
||||
HttpClient client = GetClient();
|
||||
Guid userId = scenario.TryGetValue(RegisteredUserIdKey, out Guid id)
|
||||
? id
|
||||
: Guid.NewGuid();
|
||||
Guid userId = scenario.TryGetValue(RegisteredUserIdKey, out Guid id) ? id : Guid.NewGuid();
|
||||
|
||||
HttpRequestMessage requestMessage = new(
|
||||
HttpMethod.Post,
|
||||
|
||||
@@ -8,20 +8,23 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="idunno.Password.Generator" Version="2.0.0"/>
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.2"/>
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.11"/>
|
||||
<PackageReference Include="Spectre.Console" Version="0.57.2"/>
|
||||
<PackageReference Include="idunno.Password.Generator" Version="2.0.0" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.2" />
|
||||
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.11" />
|
||||
<PackageReference Include="Spectre.Console" Version="0.57.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj"/>
|
||||
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj"/>
|
||||
<ProjectReference Include="..\..\Features\Features.Breweries\Features.Breweries.csproj"/>
|
||||
<ProjectReference Include="..\..\Features\Features.Auth\Features.Auth.csproj"/>
|
||||
<ProjectReference Include="..\..\Features\Features.Locations\Features.Locations.csproj"/>
|
||||
<ProjectReference Include="..\..\Domain\Domain.Entities\Domain.Entities.csproj" />
|
||||
<ProjectReference Include="..\..\Infrastructure\Infrastructure.Sql\Infrastructure.Sql.csproj" />
|
||||
<ProjectReference Include="..\..\Features\Features.Breweries\Features.Breweries.csproj" />
|
||||
<ProjectReference Include="..\..\Features\Features.Auth\Features.Auth.csproj" />
|
||||
<ProjectReference Include="..\..\Features\Features.Locations\Features.Locations.csproj" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None CopyToOutputDirectory="PreserveNewest" Include="SeedData\biergarten_seed_2026-08-24T01-52-09.841693Z.sqlite"/>
|
||||
<None
|
||||
CopyToOutputDirectory="PreserveNewest"
|
||||
Include="SeedData\biergarten_seed_2026-08-24T01-52-09.841693Z.sqlite"
|
||||
/>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -12,5 +12,6 @@ public class ConnectionStrings
|
||||
public static string GetSqlServerConnectionString(IConfiguration configuration) =>
|
||||
SqlConnectionStringHelper.BuildConnectionString(configuration);
|
||||
|
||||
public static string SqliteConnectionString => "Data Source=SeedData/biergarten_seed_2026-08-24T01-52-09.841693Z.sqlite";
|
||||
public static string SqliteConnectionString =>
|
||||
"Data Source=SeedData/biergarten_seed_2026-08-24T01-52-09.841693Z.sqlite";
|
||||
}
|
||||
|
||||
@@ -79,8 +79,8 @@ public sealed class NominatimReverseGeocoder : IDisposable
|
||||
|
||||
string addressLine1 = string.Join(
|
||||
' ',
|
||||
new[] { response.Address.HouseNumber, response.Address.Road }.Where(
|
||||
part => !string.IsNullOrWhiteSpace(part)
|
||||
new[] { response.Address.HouseNumber, response.Address.Road }.Where(part =>
|
||||
!string.IsNullOrWhiteSpace(part)
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -26,9 +26,7 @@ static async Task<int> RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
IConfiguration configuration = new ConfigurationBuilder()
|
||||
.AddEnvironmentVariables()
|
||||
.Build();
|
||||
IConfiguration configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();
|
||||
|
||||
ServiceCollection services = [];
|
||||
services.AddSingleton(configuration);
|
||||
@@ -39,21 +37,17 @@ static async Task<int> RunAsync()
|
||||
|
||||
await using ServiceProvider provider = services.BuildServiceProvider();
|
||||
|
||||
IBreweryRepository breweryRepository =
|
||||
provider.GetRequiredService<IBreweryRepository>();
|
||||
ILocationRepository locationRepository =
|
||||
provider.GetRequiredService<ILocationRepository>();
|
||||
UserManager<ApplicationUser> userManager =
|
||||
provider.GetRequiredService<UserManager<ApplicationUser>>();
|
||||
IBreweryRepository breweryRepository = provider.GetRequiredService<IBreweryRepository>();
|
||||
ILocationRepository locationRepository = provider.GetRequiredService<ILocationRepository>();
|
||||
UserManager<ApplicationUser> userManager = provider.GetRequiredService<
|
||||
UserManager<ApplicationUser>
|
||||
>();
|
||||
|
||||
AnsiConsole.Write(new Rule("[bold green]Database Seeder[/]")
|
||||
.LeftJustified());
|
||||
AnsiConsole.MarkupLine(
|
||||
"[grey]Connecting to SQLite source and loading seed data...[/]");
|
||||
AnsiConsole.Write(new Rule("[bold green]Database Seeder[/]").LeftJustified());
|
||||
AnsiConsole.MarkupLine("[grey]Connecting to SQLite source and loading seed data...[/]");
|
||||
AnsiConsole.WriteLine();
|
||||
|
||||
PipelineSeedDataReader reader =
|
||||
new(ConnectionStrings.SqliteConnectionString);
|
||||
PipelineSeedDataReader reader = new(ConnectionStrings.SqliteConnectionString);
|
||||
|
||||
SeedData seedData = null!;
|
||||
IReadOnlyList<Guid> postedByIds = [];
|
||||
@@ -79,16 +73,14 @@ static async Task<int> RunAsync()
|
||||
AnsiConsole.Write(BuildBreweryTable(seedData.Breweries));
|
||||
AnsiConsole.WriteLine();
|
||||
|
||||
AnsiConsole.MarkupLine(
|
||||
$"[green]✓[/] Loaded [bold]{seedData.Users.Count}[/] users.");
|
||||
AnsiConsole.MarkupLine($"[green]✓[/] Loaded [bold]{seedData.Users.Count}[/] users.");
|
||||
AnsiConsole.Write(BuildUserTable(seedData.Users));
|
||||
AnsiConsole.WriteLine();
|
||||
|
||||
AnsiConsole.WriteLine("Seed data loaded successfully.");
|
||||
|
||||
AnsiConsole.Write(
|
||||
new Rule("[bold green]Loading seed data into target database.[/]")
|
||||
.LeftJustified()
|
||||
new Rule("[bold green]Loading seed data into target database.[/]").LeftJustified()
|
||||
);
|
||||
|
||||
await AnsiConsole
|
||||
@@ -193,8 +185,7 @@ static async Task LoadBreweriesIntoDatabaseAsync(
|
||||
const string placeholderAddressLine1 = "Address unavailable";
|
||||
|
||||
if (posterUserIds.Count == 0)
|
||||
throw new InvalidOperationException(
|
||||
"Cannot load breweries without any registered users.");
|
||||
throw new InvalidOperationException("Cannot load breweries without any registered users.");
|
||||
|
||||
for (int i = 0; i < breweries.Count; i++)
|
||||
{
|
||||
@@ -294,4 +285,4 @@ static Table BuildUserTable(IReadOnlyList<UserRecord> users)
|
||||
}
|
||||
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,5 @@ public sealed class UserAccount
|
||||
public byte[]? RowVersion { get; set; }
|
||||
|
||||
// Navigation properties
|
||||
public UserCredential? UserCredential { get; set; }
|
||||
|
||||
public UserCredential? UserCredential { get; set; }
|
||||
}
|
||||
|
||||
@@ -103,7 +103,11 @@ public class RegisterUserHandlerTests
|
||||
.Setup(x => x.CreateAsync(It.IsAny<ApplicationUser>(), command.Password))
|
||||
.ReturnsAsync(
|
||||
IdentityResult.Failed(
|
||||
new IdentityError { Code = "DuplicateUserName", Description = "Username taken." }
|
||||
new IdentityError
|
||||
{
|
||||
Code = "DuplicateUserName",
|
||||
Description = "Username taken.",
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ public class ResendConfirmationEmailHandlerTests
|
||||
private readonly ResendConfirmationEmailHandler _handler;
|
||||
private readonly Mock<IMediator> _mediatorMock = new();
|
||||
private readonly Mock<ITokenService> _tokenServiceMock = new();
|
||||
private readonly Mock<UserManager<ApplicationUser>> _userManagerMock = UserManagerMockFactory.Create();
|
||||
private readonly Mock<UserManager<ApplicationUser>> _userManagerMock =
|
||||
UserManagerMockFactory.Create();
|
||||
|
||||
public ResendConfirmationEmailHandlerTests()
|
||||
{
|
||||
|
||||
@@ -87,7 +87,9 @@ public class LoginHandlerTests
|
||||
ApplicationUser user = new() { Id = Guid.NewGuid(), UserName = username };
|
||||
|
||||
_userManagerMock.Setup(x => x.FindByNameAsync(username)).ReturnsAsync(user);
|
||||
_userManagerMock.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>())).ReturnsAsync(false);
|
||||
_userManagerMock
|
||||
.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>()))
|
||||
.ReturnsAsync(false);
|
||||
|
||||
Func<Task<LoginPayload>> act = async () =>
|
||||
await _handler.Handle(new LoginCommand(username, "password"), CancellationToken.None);
|
||||
@@ -104,7 +106,9 @@ public class LoginHandlerTests
|
||||
ApplicationUser user = new() { Id = Guid.NewGuid(), UserName = username };
|
||||
|
||||
_userManagerMock.Setup(x => x.FindByNameAsync(username)).ReturnsAsync(user);
|
||||
_userManagerMock.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>())).ReturnsAsync(false);
|
||||
_userManagerMock
|
||||
.Setup(x => x.CheckPasswordAsync(user, It.IsAny<string>()))
|
||||
.ReturnsAsync(false);
|
||||
|
||||
Func<Task<LoginPayload>> act = async () =>
|
||||
await _handler.Handle(
|
||||
|
||||
@@ -29,9 +29,7 @@ public class ConfirmUserHandler(
|
||||
request.Token
|
||||
);
|
||||
|
||||
ApplicationUser? user = await userManager.FindByIdAsync(
|
||||
validatedToken.UserId.ToString()
|
||||
);
|
||||
ApplicationUser? user = await userManager.FindByIdAsync(validatedToken.UserId.ToString());
|
||||
if (user == null)
|
||||
throw new UnauthorizedException("User account not found");
|
||||
|
||||
|
||||
@@ -27,7 +27,9 @@ public class DeleteAccountHandler(UserManager<ApplicationUser> userManager)
|
||||
throw new ConflictException(
|
||||
"Account cannot be deleted while it still has associated posts, comments, photos, or follows."
|
||||
);
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,10 @@ public class LoginHandler(UserManager<ApplicationUser> userManager, ITokenServic
|
||||
/// Thrown when the username does not match any account or the supplied password does not match
|
||||
/// the stored hash.
|
||||
/// </exception>
|
||||
public async Task<LoginPayload> Handle(LoginCommand request, CancellationToken cancellationToken)
|
||||
public async Task<LoginPayload> Handle(
|
||||
LoginCommand request,
|
||||
CancellationToken cancellationToken
|
||||
)
|
||||
{
|
||||
ApplicationUser user =
|
||||
await userManager.FindByNameAsync(request.Username)
|
||||
|
||||
@@ -43,7 +43,9 @@ public class RegisterUserHandler(
|
||||
{
|
||||
if (result.Errors.Any(e => e.Code is "DuplicateUserName" or "DuplicateEmail"))
|
||||
throw new ConflictException("Username or email already exists");
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
}
|
||||
|
||||
string accessToken = tokenService.GenerateAccessToken(user.Id, user.UserName);
|
||||
@@ -51,7 +53,13 @@ public class RegisterUserHandler(
|
||||
string confirmationToken = tokenService.GenerateConfirmationToken(user.Id, user.UserName);
|
||||
|
||||
if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(refreshToken))
|
||||
return new RegistrationPayload(user.Id, user.UserName, string.Empty, string.Empty, false);
|
||||
return new RegistrationPayload(
|
||||
user.Id,
|
||||
user.UserName,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
false
|
||||
);
|
||||
|
||||
bool emailSent = false;
|
||||
try
|
||||
@@ -68,6 +76,12 @@ public class RegisterUserHandler(
|
||||
Console.WriteLine("Could not send email.");
|
||||
}
|
||||
|
||||
return new RegistrationPayload(user.Id, user.UserName, refreshToken, accessToken, emailSent);
|
||||
return new RegistrationPayload(
|
||||
user.Id,
|
||||
user.UserName,
|
||||
refreshToken,
|
||||
accessToken,
|
||||
emailSent
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,4 +11,5 @@ namespace Features.Auth.Commands.UpdateEmail;
|
||||
/// The authenticated caller's own ID, extracted from the access token -- never bind this from
|
||||
/// client-supplied input.
|
||||
/// </param>
|
||||
public record UpdateEmailCommand(Guid UserAccountId, string NewEmail) : IRequest<UpdateEmailPayload>;
|
||||
public record UpdateEmailCommand(Guid UserAccountId, string NewEmail)
|
||||
: IRequest<UpdateEmailPayload>;
|
||||
|
||||
@@ -31,7 +31,9 @@ public class UpdateEmailHandler(UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
if (result.Errors.Any(e => e.Code == "DuplicateEmail"))
|
||||
throw new ConflictException("Email address already exists");
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
}
|
||||
|
||||
return new UpdateEmailPayload(user.Id, user.Email, user.EmailConfirmed);
|
||||
|
||||
@@ -34,7 +34,9 @@ public class UpdatePasswordHandler(UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
if (result.Errors.Any(e => e.Code == "PasswordMismatch"))
|
||||
throw new UnauthorizedException("Current password is incorrect");
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
}
|
||||
|
||||
return new UpdatePasswordPayload(user.Id, DateTime.UtcNow);
|
||||
|
||||
@@ -31,7 +31,9 @@ public class UpdateProfileHandler(UserManager<ApplicationUser> userManager)
|
||||
|
||||
IdentityResult result = await userManager.UpdateAsync(user);
|
||||
if (!result.Succeeded)
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
|
||||
return new UpdateProfilePayload(user.Id, user.FirstName, user.LastName, user.DateOfBirth);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,9 @@ public class UpdateUsernameHandler(UserManager<ApplicationUser> userManager)
|
||||
{
|
||||
if (result.Errors.Any(e => e.Code == "DuplicateUserName"))
|
||||
throw new ConflictException("Username already exists");
|
||||
throw new ConflictException(string.Join("; ", result.Errors.Select(e => e.Description)));
|
||||
throw new ConflictException(
|
||||
string.Join("; ", result.Errors.Select(e => e.Description))
|
||||
);
|
||||
}
|
||||
|
||||
return new UpdateUsernamePayload(user.Id, user.UserName);
|
||||
|
||||
@@ -71,7 +71,9 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
/// </remarks>
|
||||
[AllowAnonymous]
|
||||
[HttpPost("login")]
|
||||
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login([FromBody] LoginCommand command)
|
||||
public async Task<ActionResult<ResponseBody<LoginPayload>>> Login(
|
||||
[FromBody] LoginCommand command
|
||||
)
|
||||
{
|
||||
LoginPayload payload = await mediator.Send(command);
|
||||
return Ok(
|
||||
|
||||
@@ -22,6 +22,6 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="Queries\" />
|
||||
<Folder Include="Queries\" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -19,8 +19,7 @@ public sealed class DapperUserStore(ISqlConnectionFactory connectionFactory)
|
||||
IUserPasswordStore<ApplicationUser>,
|
||||
IUserEmailStore<ApplicationUser>
|
||||
{
|
||||
private const string SelectUserSql =
|
||||
"""
|
||||
private const string SelectUserSql = """
|
||||
SELECT UserAccountID AS Id, Username AS UserName, FirstName, LastName, Email, DateOfBirth
|
||||
FROM dbo.UserAccount
|
||||
""";
|
||||
@@ -33,8 +32,10 @@ public sealed class DapperUserStore(ISqlConnectionFactory connectionFactory)
|
||||
Task.FromResult(user.Id.ToString());
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<string?> GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken) =>
|
||||
Task.FromResult<string?>(user.UserName);
|
||||
public Task<string?> GetUserNameAsync(
|
||||
ApplicationUser user,
|
||||
CancellationToken cancellationToken
|
||||
) => Task.FromResult<string?>(user.UserName);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task SetUserNameAsync(
|
||||
|
||||
@@ -21,7 +21,12 @@ public enum TokenType
|
||||
public record ValidatedToken(Guid UserId, string Username, ClaimsPrincipal Principal);
|
||||
|
||||
/// <summary>Represents the result of refreshing a user's session.</summary>
|
||||
public record RefreshTokenResult(Guid UserId, string Username, string RefreshToken, string AccessToken);
|
||||
public record RefreshTokenResult(
|
||||
Guid UserId,
|
||||
string Username,
|
||||
string RefreshToken,
|
||||
string AccessToken
|
||||
);
|
||||
|
||||
/// <summary>
|
||||
/// Defines the expiration windows, in hours, for each type of token issued by <see cref="ITokenService" />.
|
||||
@@ -61,7 +66,6 @@ public interface ITokenService
|
||||
/// </summary>
|
||||
string GenerateConfirmationToken(Guid userId, string username);
|
||||
|
||||
|
||||
/// <summary>Validates an access token's signature and expiration and extracts the caller's identity.</summary>
|
||||
/// <exception cref="Domain.Exceptions.UnauthorizedException">
|
||||
/// Thrown when the token is missing required claims, has a malformed user ID, or otherwise fails validation.
|
||||
|
||||
@@ -23,9 +23,7 @@ public class CreateBreweryValidator : AbstractValidator<CreateBreweryCommand>
|
||||
|
||||
RuleFor(x => x.Location).NotNull().WithMessage("Location is required.");
|
||||
|
||||
RuleFor(x => x.Location.CityId)
|
||||
.NotEmpty()
|
||||
.WithMessage("CityId is required.");
|
||||
RuleFor(x => x.Location.CityId).NotEmpty().WithMessage("CityId is required.");
|
||||
|
||||
RuleFor(x => x.Location.AddressLine1)
|
||||
.NotEmpty()
|
||||
|
||||
@@ -70,8 +70,7 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit,
|
||||
int? offset)
|
||||
public async Task<IEnumerable<BreweryPost>> GetAllAsync(int? limit, int? offset)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
return await connection.QueryAsync<
|
||||
@@ -122,25 +121,24 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
public async Task<BreweryPost> UpdateAsync(BreweryPost brewery)
|
||||
{
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbTransaction transaction =
|
||||
await connection.BeginTransactionAsync();
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync();
|
||||
|
||||
try
|
||||
{
|
||||
bool breweryExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1 FROM
|
||||
dbo.BreweryPost
|
||||
WHERE
|
||||
BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1 FROM
|
||||
dbo.BreweryPost
|
||||
WHERE
|
||||
BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!breweryExists)
|
||||
throw new NotFoundException("Brewery not found.");
|
||||
@@ -149,13 +147,13 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
bool cityExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"SELECT 1 FROM dbo.City WHERE CityID = @CityId",
|
||||
new { brewery.Location.CityId },
|
||||
transaction
|
||||
)
|
||||
new CommandDefinition(
|
||||
"SELECT 1 FROM dbo.City WHERE CityID = @CityId",
|
||||
new { brewery.Location.CityId },
|
||||
transaction
|
||||
)
|
||||
is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!cityExists)
|
||||
throw new NotFoundException("City not found.");
|
||||
@@ -207,17 +205,17 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
{
|
||||
bool locationExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.BreweryPostLocation
|
||||
WHERE BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM dbo.BreweryPostLocation
|
||||
WHERE BreweryPostID = @BreweryPostId
|
||||
""",
|
||||
new { brewery.BreweryPostId },
|
||||
transaction
|
||||
)
|
||||
is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (locationExists)
|
||||
await connection.ExecuteAsync(
|
||||
@@ -288,9 +286,9 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
}
|
||||
|
||||
return await GetByIdAsync(brewery.BreweryPostId)
|
||||
?? throw new InvalidOperationException(
|
||||
$"Brewery '{brewery.BreweryPostId}' was not found after a successful update."
|
||||
);
|
||||
?? throw new InvalidOperationException(
|
||||
$"Brewery '{brewery.BreweryPostId}' was not found after a successful update."
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
@@ -315,49 +313,47 @@ public class BreweryRepository(ISqlConnectionFactory connectionFactory)
|
||||
public async Task CreateAsync(BreweryPost brewery)
|
||||
{
|
||||
if (brewery.Location is null)
|
||||
throw new ArgumentException(
|
||||
"Location must be provided when creating a brewery.");
|
||||
throw new ArgumentException("Location must be provided when creating a brewery.");
|
||||
|
||||
await using DbConnection connection = await CreateConnection();
|
||||
await using DbTransaction transaction =
|
||||
await connection.BeginTransactionAsync();
|
||||
await using DbTransaction transaction = await connection.BeginTransactionAsync();
|
||||
|
||||
try
|
||||
{
|
||||
bool userExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM
|
||||
dbo.UserAccount
|
||||
WHERE
|
||||
UserAccountID = @PostedById
|
||||
""",
|
||||
new { brewery.PostedById },
|
||||
transaction
|
||||
)
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM
|
||||
dbo.UserAccount
|
||||
WHERE
|
||||
UserAccountID = @PostedById
|
||||
""",
|
||||
new { brewery.PostedById },
|
||||
transaction
|
||||
)
|
||||
is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!userExists)
|
||||
throw new NotFoundException("User not found.");
|
||||
|
||||
bool cityExists =
|
||||
await connection.ExecuteScalarAsync<int?>(
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM
|
||||
dbo.City
|
||||
WHERE
|
||||
CityID = @CityId
|
||||
""",
|
||||
new { brewery.Location.CityId },
|
||||
transaction
|
||||
)
|
||||
new CommandDefinition(
|
||||
"""
|
||||
SELECT 1
|
||||
FROM
|
||||
dbo.City
|
||||
WHERE
|
||||
CityID = @CityId
|
||||
""",
|
||||
new { brewery.Location.CityId },
|
||||
transaction
|
||||
)
|
||||
is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!cityExists)
|
||||
throw new NotFoundException("City not found.");
|
||||
|
||||
@@ -51,7 +51,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
|
||||
WHERE CityName = @CityName AND StateProvinceID = @StateProvinceId
|
||||
""",
|
||||
new { location.CityName, StateProvinceId = stateProvinceId }
|
||||
) is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!cityExists)
|
||||
await connection.ExecuteAsync(
|
||||
@@ -83,7 +84,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
|
||||
WHERE ISO3166_1 = @ISO3166_1
|
||||
""",
|
||||
new { ISO3166_1 = isoCode }
|
||||
) is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!exists)
|
||||
// A concurrent caller may create this country between the check above and here; that
|
||||
@@ -128,7 +130,8 @@ public class LocationRepository(ISqlConnectionFactory connectionFactory)
|
||||
WHERE ISO3166_2 = @ISO3166_2
|
||||
""",
|
||||
new { ISO3166_2 = isoCode }
|
||||
) is not null;
|
||||
)
|
||||
is not null;
|
||||
|
||||
if (!exists)
|
||||
await connection.ExecuteAsync(
|
||||
|
||||
@@ -52,8 +52,7 @@ public static class SqlConnectionStringHelper
|
||||
return !bool.TryParse(
|
||||
configuration["DB_TRUST_SERVER_CERTIFICATE"],
|
||||
out bool trustServerCertificate
|
||||
)
|
||||
|| trustServerCertificate;
|
||||
) || trustServerCertificate;
|
||||
}
|
||||
|
||||
private static string Required(IConfiguration configuration, string key) =>
|
||||
|
||||
@@ -1 +1 @@
|
||||
namespace Infrastructure.Sql;
|
||||
namespace Infrastructure.Sql;
|
||||
|
||||
Reference in New Issue
Block a user