Skip to content
This repository has been archived by the owner on Sep 3, 2023. It is now read-only.

Commit

Permalink
Merge pull request #338 from kysect/feat/seeding-endpoint-321
Browse files Browse the repository at this point in the history
feat: Moved InitTestEnvironment method from startup to separate controller
  • Loading branch information
xrem authored Sep 5, 2022
2 parents dbd0864 + eb3192b commit 08afa80
Show file tree
Hide file tree
Showing 6 changed files with 137 additions and 35 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using MediatR;

namespace Kysect.Shreks.Application.Abstractions.Internal;

public static class SeedTestData
{
public record Query(string Environment) : IRequest<Unit>;

public class UserNotAcknowledgedEnvironmentException : InvalidOperationException
{
public UserNotAcknowledgedEnvironmentException()
: base("You must ensure that is it a right environment to execute SeedTestData command")
{
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Kysect.Shreks.Core.Study;
using Kysect.Shreks.Core.SubjectCourseAssociations;
using Kysect.Shreks.Core.UserAssociations;
using Kysect.Shreks.Core.Users;
using Kysect.Shreks.DataAccess.Abstractions;
using Kysect.Shreks.Playground.Github.TestEnv;
using Kysect.Shreks.Seeding.EntityGenerators;
using MediatR;
using static Kysect.Shreks.Application.Abstractions.Internal.SeedTestData;

namespace Kysect.Shreks.Application.Handlers.Internal;

public class SeedTestDataHandler : IRequestHandler<Query>
{
private const string ExceptedEnvironment = "Testing";

private readonly IShreksDatabaseContext _context;
private readonly IEntityGenerator<User> _userGenerator;
private readonly IEntityGenerator<SubjectCourse> _subjectCourseGenerator;
private readonly TestEnvironmentConfiguration _configuration;

public SeedTestDataHandler(
IShreksDatabaseContext context,
IEntityGenerator<User> userGenerator,
IEntityGenerator<SubjectCourse> subjectCourseGenerator,
TestEnvironmentConfiguration configuration)
{
_context = context;
_userGenerator = userGenerator;
_subjectCourseGenerator = subjectCourseGenerator;
_configuration = configuration;
}

public async Task<Unit> Handle(Query request, CancellationToken cancellationToken = default)
{
EnsureUserAcknowledgedEnvironment(request);
AddUsers();
AddGithubUserAssociations();

await _context.SaveChangesAsync(cancellationToken);

return Unit.Value;
}

private static void EnsureUserAcknowledgedEnvironment(Query request)
{
if (!request.Environment.Equals(ExceptedEnvironment, StringComparison.OrdinalIgnoreCase))
{
throw new UserNotAcknowledgedEnvironmentException();
}
}

private void AddGithubUserAssociations()
{
SubjectCourse subjectCourse = _subjectCourseGenerator.GeneratedEntities[0];
_context.SubjectCourses.Attach(subjectCourse);
_context.SubjectCourseAssociations.Add(
new GithubSubjectCourseAssociation(subjectCourse, _configuration.Organization,
_configuration.TemplateRepository));
}

private void AddUsers()
{
IReadOnlyList<User> users = _userGenerator.GeneratedEntities;
_context.Users.AttachRange(users);

for (var index = 0; index < _configuration.Users.Count; index++)
{
User user = users[index];
string login = _configuration.Users[index];
_context.UserAssociations.Add(new GithubUserAssociation(user, login));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\Infrastructure\Integration\Kysect.Shreks.Integration.Github\Kysect.Shreks.Integration.Github.csproj" />
<ProjectReference Include="..\..\Infrastructure\Kysect.Shreks.Identity\Kysect.Shreks.Identity.csproj" />
<ProjectReference Include="..\..\Infrastructure\Kysect.Shreks.Seeding\Kysect.Shreks.Seeding.csproj" />
<ProjectReference Include="..\Kysect.Shreks.Application\Kysect.Shreks.Application.csproj" />
<ProjectReference Include="..\Kysect.Shreks.DataAccess.Abstractions\Kysect.Shreks.DataAccess.Abstractions.csproj" />
</ItemGroup>
Expand Down
42 changes: 42 additions & 0 deletions Source/Kysect.Shreks.WebApi/Controllers/InternalController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Net;
using Kysect.Shreks.Identity.Entities;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using static Kysect.Shreks.Application.Abstractions.Internal.SeedTestData;

namespace Kysect.Shreks.WebApi.Controllers;

[ApiController]
[Route("api/internal/")]
[Authorize(Roles = ShreksIdentityRole.AdminRoleName)]
public class InternalController : ControllerBase
{
private readonly IMediator _mediator;

public InternalController(IMediator mediator)
{
_mediator = mediator;
}

[HttpPost("seed-test-data")]
public async Task<IActionResult> SeedTestData([FromQuery] string environment)
{
var command = new Query(environment);
try
{
await _mediator.Send(command);
}
catch (UserNotAcknowledgedEnvironmentException e)
{
return StatusCode((int) HttpStatusCode.BadRequest, new ProblemDetails
{
Status = (int) HttpStatusCode.BadRequest,
Title = e.Message,
Detail = "You must put string 'Testing' into environment field if you have 100% ensured that it is not a production environment"
});
}

return NoContent();
}
}
38 changes: 3 additions & 35 deletions Source/Kysect.Shreks.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Kysect.Shreks.Core.Submissions;
using Kysect.Shreks.Core.UserAssociations;
using Kysect.Shreks.Core.Users;
using Kysect.Shreks.DataAccess.Abstractions;
using Kysect.Shreks.DataAccess.Configuration;
using Kysect.Shreks.DataAccess.Extensions;
using Kysect.Shreks.Identity.Extensions;
Expand All @@ -19,12 +18,12 @@
using Kysect.Shreks.Integration.Google.Models;
using Kysect.Shreks.Mapping.Extensions;
using Kysect.Shreks.Playground.Github.TestEnv;
using Kysect.Shreks.Seeding.EntityGenerators;
using Kysect.Shreks.Seeding.Extensions;
using Kysect.Shreks.WebApi.Filters;
using Kysect.Shreks.WebApi.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.OpenApi.Models;
using Serilog;

Expand All @@ -49,6 +48,7 @@

void InitServiceCollection(WebApplicationBuilder webApplicationBuilder)
{
webApplicationBuilder.Services.TryAddSingleton(testEnvironmentConfiguration);
webApplicationBuilder.Services.AddControllers(x => x.Filters.Add<AuthenticationFilter>()).AddNewtonsoftJson();
webApplicationBuilder.Services.AddEndpointsApiExplorer();
webApplicationBuilder.Services.AddSwaggerGen(c =>
Expand Down Expand Up @@ -163,44 +163,12 @@ async Task InitWebApplication(WebApplicationBuilder webApplicationBuilder)

using (var scope = app.Services.CreateScope())
{
if (app.Environment.IsDevelopment())
await InitTestEnvironment(scope.ServiceProvider, testEnvironmentConfiguration);

await SeedAdmins(scope.ServiceProvider, app.Configuration);
await SeedAdmins(scope.ServiceProvider, app.Configuration);
}

app.Run();
}

async Task InitTestEnvironment(
IServiceProvider serviceProvider,
TestEnvironmentConfiguration config,
CancellationToken cancellationToken = default)
{
return;
var dbContext = serviceProvider.GetRequiredService<IShreksDatabaseContext>();

var userGenerator = serviceProvider.GetRequiredService<IEntityGenerator<User>>();
var users = userGenerator.GeneratedEntities;
dbContext.Users.AttachRange(users);

for (var index = 0; index < config.Users.Count; index++)
{
var user = users[index];
var login = config.Users[index];
dbContext.UserAssociations.Add(new GithubUserAssociation(user, login));
}


var subjectCourseGenerator = serviceProvider.GetRequiredService<IEntityGenerator<SubjectCourse>>();
var subjectCourse = subjectCourseGenerator.GeneratedEntities[0];
dbContext.SubjectCourses.Attach(subjectCourse);
dbContext.SubjectCourseAssociations.Add(
new GithubSubjectCourseAssociation(subjectCourse, config.Organization, config.TemplateRepository));

await dbContext.SaveChangesAsync(cancellationToken);
}

async Task SeedAdmins(IServiceProvider provider, IConfiguration configuration)
{
var mediatr = provider.GetRequiredService<IMediator>();
Expand Down

0 comments on commit 08afa80

Please sign in to comment.