70 lines
1.9 KiB
C#
70 lines
1.9 KiB
C#
using Dapper;
|
|
using Shogi.Api.Repositories.Dto;
|
|
using Shogi.Domain;
|
|
using Shogi.Domain.Aggregates;
|
|
using Shogi.Domain.ValueObjects;
|
|
using System.Data;
|
|
using System.Data.SqlClient;
|
|
using System.Text.Json;
|
|
|
|
namespace Shogi.Api.Repositories;
|
|
|
|
public class SessionRepository : ISessionRepository
|
|
{
|
|
private readonly string connectionString;
|
|
|
|
public SessionRepository(IConfiguration configuration)
|
|
{
|
|
connectionString = configuration.GetConnectionString("ShogiDatabase");
|
|
}
|
|
|
|
public async Task CreateSession(Session session)
|
|
{
|
|
var boardStateDto = new BoardStateDto
|
|
{
|
|
InCheck = session.BoardState.InCheck,
|
|
IsCheckmate = session.BoardState.IsCheckmate,
|
|
Player1Hand = session.BoardState.Player1Hand,
|
|
Player2Hand = session.BoardState.Player2Hand,
|
|
State = session.BoardState.State,
|
|
WhoseTurn = session.BoardState.WhoseTurn,
|
|
};
|
|
|
|
using var connection = new SqlConnection(connectionString);
|
|
await connection.ExecuteAsync(
|
|
"session.CreateSession",
|
|
new
|
|
{
|
|
Name = sessionName,
|
|
InitialBoardStateDocument = JsonSerializer.Serialize(boardStateDto),
|
|
Player1Name = player1,
|
|
},
|
|
commandType: CommandType.StoredProcedure);
|
|
}
|
|
|
|
public async Task<ShogiBoard?> ReadShogiBoard(string name)
|
|
{
|
|
using var connection = new SqlConnection(connectionString);
|
|
var results = await connection.QueryAsync<SessionDto>(
|
|
"session.ReadSession",
|
|
commandType: CommandType.StoredProcedure);
|
|
var dto = results.SingleOrDefault();
|
|
if (dto == null) return null;
|
|
|
|
var boardState = new BoardState(
|
|
state: new(dto.BoardState.State),
|
|
player1Hand: dto.BoardState.Player1Hand,
|
|
player2Hand: dto.BoardState.Player2Hand,
|
|
whoseTurn: dto.BoardState.WhoseTurn,
|
|
playerInCheck: dto.BoardState.InCheck,
|
|
previousMove: dto.BoardState.PreviousMove);
|
|
var session = new ShogiBoard(boardState);
|
|
return session;
|
|
}
|
|
}
|
|
|
|
public interface ISessionRepository
|
|
{
|
|
Task CreateSession(Session session);
|
|
Task<ShogiBoard?> ReadShogiBoard(string name);
|
|
} |