Updated lots of stuff, got multi scrape working, need to test not-nullable chapter novel ids with our current model, now supports sqlite and postgres concurrently (and easy add more), need to get it deployed/do auth
Some checks failed
continuous-integration/drone/push Build is failing

This commit is contained in:
2022-07-16 17:17:43 -04:00
parent eab3399268
commit d98324c11e
73 changed files with 1591 additions and 680 deletions

View File

@@ -0,0 +1,75 @@
using System.Reflection;
using DBConnection.ModelBuilders;
using DBConnection.Seeders;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Treestar.Shared.Models.DBDomain;
namespace DBConnection.Contexts;
public abstract class AppDbContext : DbContext
{
public DbSet<Novel> Novels { get; set; }
public DbSet<Chapter> Chapters { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Tag> Tags { get; set; }
public DbSet<UserNovel> UserNovels { get; set; }
protected IConfiguration Configuration { get; set; }
protected abstract string ConnectionStringName { get; }
private readonly IEnumerable<ISeeder> _seeders =
from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && (t.Namespace?.Contains(nameof(DBConnection.Seeders)) ?? false) && typeof(ISeeder).IsAssignableFrom(t)
select (ISeeder) Activator.CreateInstance(t);
private static readonly IEnumerable<IModelBuilder> ModelBuilders =
from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && (t.Namespace?.Contains(nameof(DBConnection.ModelBuilders)) ?? false) && typeof(IModelBuilder).IsAssignableFrom(t)
select (IModelBuilder) Activator.CreateInstance(t);
protected AppDbContext(DbContextOptions options, IConfiguration configuration) : base(options)
{
Configuration = configuration;
}
public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
UpdateAuditInfo();
return base.SaveChangesAsync(cancellationToken);
}
private void UpdateAuditInfo()
{
var entries = ChangeTracker.Entries().Where(x =>
x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach(var entry in entries) {
if (entry.State == EntityState.Added)
{
((BaseEntity)entry.Entity).DateCreated = DateTime.Now;
}
((BaseEntity)entry.Entity).DateModified = DateTime.Now;
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var builder in ModelBuilders)
{
builder.BuildModel(modelBuilder);
}
foreach (var seeder in _seeders)
{
seeder.SeedData(modelBuilder);
}
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
UseSqlConnection(optionsBuilder, Configuration.GetConnectionString(ConnectionStringName));
}
protected abstract void UseSqlConnection(DbContextOptionsBuilder builder, string connectionString);
}