Skip to content

Commit

Permalink
✨ Heroes domain now has seed data (#305)
Browse files Browse the repository at this point in the history
Heroes domain now has seed data
  • Loading branch information
danielmackay authored May 16, 2024
1 parent 20dd2a9 commit 6c4ca2d
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 14 deletions.
5 changes: 4 additions & 1 deletion src/Domain/Teams/Mission.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ public class Mission : Entity<MissionId>
internal static Mission Create(string description)
{
Guard.Against.NullOrWhiteSpace(description);
return new Mission { Description = description, Status = MissionStatus.InProgress };
return new Mission
{
Id = new MissionId(Guid.NewGuid()), Description = description, Status = MissionStatus.InProgress
};
}

internal void Complete()
Expand Down
122 changes: 111 additions & 11 deletions src/Infrastructure/Persistence/ApplicationDbContextInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,67 @@
using Microsoft.Extensions.Logging;
using SSW.CleanArchitecture.Domain.TodoItems;
using Bogus;
using SSW.CleanArchitecture.Domain.Heroes;
using SSW.CleanArchitecture.Domain.Teams;

namespace SSW.CleanArchitecture.Infrastructure.Persistence;

public class ApplicationDbContextInitializer(
ILogger<ApplicationDbContextInitializer> logger,
ApplicationDbContext dbContext)
{
private const int NumTodoItems = 20;
private readonly string[] _superHeroNames =
[
"Superman",
"Batman",
"Wonder Woman",
"Flash", "Aquaman",
"Cyborg",
"Green Lantern",
"Shazam",
"Captain Marvel",
"Cyclops",
"Wolverine",
"Storm"
];

private readonly string[] _superPowers =
[
"Strength",
"Flight",
"Invulnerability",
"Speed",
"Heat Vision",
"X-Ray Vision",
"Hearing",
"Healing Factor",
"Agility",
"Stamina",
"Breath",
"Weapons",
"Intelligence"
];

private readonly string[] _teamNames =
[
"Marvel",
"Avengers",
"DC",
"Justice League",
"X-Men"
];

private readonly string[] _missionNames =
[
"Save the world",
"Rescue the hostages",
"Defeat the villain",
"Stop the bomb",
"Protect the city"
];

private const int NumHeroes = 20;
private const int NumTeams = 5;

public async Task InitializeAsync()
{
Expand All @@ -31,21 +84,68 @@ public async Task SeedAsync()
{
try
{
if (dbContext.TodoItems.Any())
return;

var faker = new Faker<TodoItem>()
.CustomInstantiator(f => TodoItem.Create(
f.Lorem.Sentence(3), f.Lorem.Sentence(10), f.Random.Enum<PriorityLevel>(), f.Date.Future(1, DateTime.UtcNow)));

var todoItems = faker.Generate(NumTodoItems);
await dbContext.TodoItems.AddRangeAsync(todoItems);
await dbContext.SaveChangesAsync();
var heroes = await SeedHeroes();
await SeedTeams(heroes);
}
catch (Exception e)
{
logger.LogError(e, "An error occurred while seeding the database");
throw;
}
}


private async Task<List<Hero>> SeedHeroes()
{
if (dbContext.Heroes.Any())
return [];

var faker = new Faker<Hero>()
.CustomInstantiator(f =>
{
var name = f.PickRandom(_superHeroNames);
var hero = Hero.Create(name, name.Substring(0, 2));
var powers = f.PickRandom(_superPowers, f.Random.Number(1, 3))
.Select(p => new Power(p, f.Random.Number(1, 10)));
hero.UpdatePowers(powers);
return hero;
});

var heroes = faker.Generate(NumHeroes);
await dbContext.Heroes.AddRangeAsync(heroes);
await dbContext.SaveChangesAsync();

return heroes;
}

private async Task SeedTeams(List<Hero> heroes)
{
if (dbContext.Teams.Any())
return;

var faker = new Faker<Team>()
.CustomInstantiator(f =>
{
var name = f.PickRandom(_teamNames);
var team = Team.Create(name);
var heroesToAdd = f.PickRandom(heroes, f.Random.Number(2, 5));

foreach (var hero in heroesToAdd)
team.AddHero(hero);

var sendOnMission = f.Lorem.Random.Bool();

if (sendOnMission)
{
var missionName = f.PickRandom(_missionNames);
team.ExecuteMission(missionName);
}

return team;
});

var teams = faker.Generate(NumTeams);
await dbContext.Teams.AddRangeAsync(teams);
await dbContext.SaveChangesAsync();
}
}
4 changes: 2 additions & 2 deletions src/WebApi/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
// NOTE: If any of your connection strings real passwords, you should delete them and put them in the user secrets file instead.
"ConnectionStrings": {
// Local DB
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CleanArchitecture;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
//"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=CleanArchitecture;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
// Docker DB
//"DefaultConnection": "Server=localhost,1433;Initial Catalog=CleanArchitecture;Persist Security Info=False;User ID=sa;Password=yourStrong(!)Password;MultipleActiveResultSets=True;TrustServerCertificate=True;Connection Timeout=30;"
"DefaultConnection": "Server=localhost,1433;Initial Catalog=CleanArchitecture;Persist Security Info=False;User ID=sa;Password=yourStrong(!)Password;MultipleActiveResultSets=True;TrustServerCertificate=True;Connection Timeout=30;"
}
}

0 comments on commit 6c4ca2d

Please sign in to comment.