51 lines
2.0 KiB
C#
51 lines
2.0 KiB
C#
using System.Data;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using Dapper;
|
|
using PlotLine.Models.WritingSolver;
|
|
using PlotLine.Services;
|
|
namespace PlotLine.Data;
|
|
|
|
public interface IWritingSolverRepository
|
|
{
|
|
Task<SolverGraph> GetAsync();
|
|
Task PublishAsync(string json, string editor);
|
|
}
|
|
|
|
public sealed class WritingSolverRepository(ISqlConnectionFactory connections) : IWritingSolverRepository
|
|
{
|
|
private static readonly object CacheLock = new();
|
|
private static (string Json, SolverGraph Graph)? cached;
|
|
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;
|
|
}
|
|
public async Task<SolverGraph> GetAsync()
|
|
{
|
|
using var connection = connections.CreateConnection();
|
|
var json = await connection.QuerySingleAsync<string>("dbo.WritingSolver_Get", commandType: CommandType.StoredProcedure);
|
|
lock (CacheLock)
|
|
{
|
|
if (cached is { } current && current.Json == json) return current.Graph;
|
|
var graph = Parse(json);
|
|
cached = (json, graph);
|
|
return graph;
|
|
}
|
|
}
|
|
public async Task PublishAsync(string json, string editor)
|
|
{
|
|
var graph = Parse(json); // Validate the entire artifact before opening a database connection.
|
|
using var connection = connections.CreateConnection();
|
|
await connection.ExecuteAsync("dbo.WritingSolver_Publish", new { graph.Version, GraphJson = JsonSerializer.Serialize(graph, JsonOptions), Editor = editor }, commandType: CommandType.StoredProcedure);
|
|
}
|
|
}
|