25 lines
1.1 KiB
C#
25 lines
1.1 KiB
C#
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using PlotDirector.Website.Models.WritingSolver;
|
|
using PlotDirector.Website.Services;
|
|
namespace PlotDirector.Website.Data;
|
|
public interface IWritingSolverRepository { Task<SolverGraph> GetAsync(); }
|
|
public sealed class WritingSolverRepository(IWebHostEnvironment environment) : IWritingSolverRepository
|
|
{
|
|
public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
|
|
{
|
|
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
|
|
RespectNullableAnnotations = true,
|
|
WriteIndented = true
|
|
};
|
|
public static SolverGraph Parse(string json)
|
|
{
|
|
var graph = JsonSerializer.Deserialize<SolverGraph>(json, JsonOptions) ?? throw new InvalidDataException("Empty graph.");
|
|
var errors = WritingSolverValidator.Validate(graph);
|
|
if (errors.Count > 0) throw new InvalidDataException(string.Join("\n", errors));
|
|
return graph;
|
|
}
|
|
private SolverGraph? graph;
|
|
public Task<SolverGraph> GetAsync() => Task.FromResult(graph ??= Parse(File.ReadAllText(Path.Combine(environment.ContentRootPath,"Content/solver.json"))));
|
|
}
|