using System.Data; using System.Text.Json; using Dapper; using PlotLine.Models; namespace PlotLine.Data; public sealed class MapRepository(ISqlConnectionFactory connections) { public async Task> ListAsync(int projectId, int userId) { using var db = connections.CreateConnection(); return (await db.QueryAsync("dbo.StoryMap_List", new { ProjectID = projectId, UserID = userId }, commandType: CommandType.StoredProcedure)).ToList(); } public async Task GetAsync(int projectId, int mapId, int userId) { using var db = connections.CreateConnection(); using var rows = await db.QueryMultipleAsync("dbo.StoryMap_Get", new { ProjectID = projectId, MapID = mapId, UserID = userId }, commandType: CommandType.StoredProcedure); var map = await rows.ReadSingleOrDefaultAsync(); var features = (await rows.ReadAsync()).ToList(); var relationships = (await rows.ReadAsync()).ToList(); return map is null ? null : new() { Map = map, Features = features, Relationships = relationships }; } public async Task CreateAsync(StoryMap map, int userId) { using var db = connections.CreateConnection(); return await db.QuerySingleAsync("dbo.StoryMap_Create", new { map.ProjectID, UserID = userId, map.Name, map.Kind, map.ParentMapID, map.ParentFeatureID }, commandType: CommandType.StoredProcedure); } public async Task SaveAsync(MapDocument document, int userId) { using var db = connections.CreateConnection(); await db.ExecuteAsync("dbo.StoryMap_Save", new { document.Map.ProjectID, document.Map.MapID, UserID = userId, document.Map.Revision, document.Map.Name, document.Map.Kind, Features = JsonSerializer.Serialize(document.Features), Relationships = JsonSerializer.Serialize(document.Relationships) }, commandType: CommandType.StoredProcedure); } public async Task DeleteAsync(int projectId, int mapId, int revision, int userId) { using var db = connections.CreateConnection(); await db.ExecuteAsync("dbo.StoryMap_Delete", new { ProjectID = projectId, MapID = mapId, Revision = revision, UserID = userId }, commandType: CommandType.StoredProcedure); } }