feat(Core): add AppConfig database table and logic

This commit is contained in:
2026-06-13 23:19:35 +02:00
parent 0c39c6169d
commit 6d228214f9
12 changed files with 210 additions and 4 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
using Core.Enums; using Core.Enums;
using Core.Models;
using Core.Responses; using Core.Responses;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -29,7 +30,7 @@ public class McoController : Controller
[HttpGet("v1/news")] [HttpGet("v1/news")]
public ActionResult GetNews() public ActionResult GetNews()
{ {
var newsResponse = new News { NewsLink = "https://github.com/CyberL1/Minecraft-Realms-Emulator" }; var newsResponse = new News { NewsLink = AppConfig.NewsLink };
return Ok(newsResponse); return Ok(newsResponse);
} }
} }
+2 -1
View File
@@ -1,3 +1,4 @@
using Core.Models;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace Core.Controllers; namespace Core.Controllers;
@@ -9,6 +10,6 @@ public class TrialController : Controller
[HttpGet] [HttpGet]
public ActionResult GetTrial() public ActionResult GetTrial()
{ {
return Ok(true); return Ok(AppConfig.Trial);
} }
} }
+5
View File
@@ -8,6 +8,11 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9"/> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.9"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2"/> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="10.0.2"/>
</ItemGroup> </ItemGroup>
+9
View File
@@ -0,0 +1,9 @@
using Core.Entities;
using Microsoft.EntityFrameworkCore;
namespace Core.Data;
public class DataContext(DbContextOptions<DataContext> options) : DbContext(options)
{
public DbSet<AppConfig> AppConfig { get; set; }
}
+12
View File
@@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Core.Entities;
[PrimaryKey("Key")]
public class AppConfig
{
public required string Key { get; set; }
[Column(TypeName = "jsonb")] public required dynamic Value { get; set; }
}
+40
View File
@@ -0,0 +1,40 @@
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace Core.Helpers;
public class AppConfig
{
private static readonly AppConfig AppConfigTyped = new();
public static void InitializeAppConfig(IServiceProvider serviceProvider)
{
using var scope = serviceProvider.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<DataContext>();
db.Database.Migrate();
var appConfigModel = new Models.AppConfig();
var properties = appConfigModel.GetType().GetProperties();
var defaultConfig = properties.Select(property => new Entities.AppConfig
{
Key = property.Name,
Value = JsonConvert.SerializeObject(property.GetValue(appConfigModel))
});
foreach (var config in defaultConfig)
db.Database.ExecuteSqlInterpolated(
$"""INSERT INTO "AppConfig" ("Key", "Value") VALUES ({config.Key}, {config.Value}::jsonb) ON CONFLICT ("Key") DO NOTHING""");
var dbConfigs = db.AppConfig.ToDictionary(p => p.Key, p => p.Value);
foreach (var property in properties)
if (dbConfigs.TryGetValue(property.Name, out var dbJsonValue) && dbJsonValue != null)
{
var deserializedValue = JsonConvert.DeserializeObject(dbJsonValue, property.PropertyType);
property.SetValue(AppConfigTyped, deserializedValue);
}
}
}
@@ -0,0 +1,43 @@
// <auto-generated />
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Core.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20260613101031_AppConfig_Init")]
partial class AppConfig_Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Core.Entities.AppConfig", b =>
{
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb");
b.HasKey("Key");
b.ToTable("AppConfig");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,33 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Core.Migrations
{
/// <inheritdoc />
public partial class AppConfig_Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AppConfig",
columns: table => new
{
Key = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "jsonb", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AppConfig", x => x.Key);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AppConfig");
}
}
}
@@ -0,0 +1,40 @@
// <auto-generated />
using Core.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Core.Migrations
{
[DbContext(typeof(DataContext))]
partial class DataContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "10.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Core.Entities.AppConfig", b =>
{
b.Property<string>("Key")
.HasColumnType("text");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("jsonb");
b.HasKey("Key");
b.ToTable("AppConfig");
});
#pragma warning restore 612, 618
}
}
}
+7
View File
@@ -0,0 +1,7 @@
namespace Core.Models;
public class AppConfig
{
public static string NewsLink { get; set; } = "https://github.com/CyberL1/Minecraft-Realms-Emulator";
public static bool Trial { get; set; } = true;
}
+16 -2
View File
@@ -1,12 +1,26 @@
using AuthorizationMiddleware = Core.Middlewares.AuthorizationMiddleware; using Core.Data;
using Core.Helpers;
using Core.Middlewares;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); builder.Services.AddControllers();
var connectionString = builder.Configuration.GetValue<string>("Database");
if (string.IsNullOrEmpty(connectionString))
{
Console.WriteLine("No database specified. Ensure 'Database' field exists in appsettings.json file.");
return;
}
builder.Services.AddDbContextPool<DataContext>(options => options.UseNpgsql(connectionString));
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. AppConfig.InitializeAppConfig(app.Services);
if (!app.Environment.IsDevelopment()) if (!app.Environment.IsDevelopment())
{ {
app.UseHttpsRedirection(); app.UseHttpsRedirection();
+1
View File
@@ -1,4 +1,5 @@
{ {
"Database": "Host=localhost;Username=postgres;Password=postgres;Database=Minecraft-Realms-Emulator",
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",