Files
Shogi/Shogi.UI/Shared/ShogiApi.cs
2024-10-20 22:27:08 -05:00

80 lines
2.4 KiB
C#

using Shogi.Contracts.Api;
using Shogi.Contracts.Types;
using System.Net;
using System.Net.Http.Json;
using System.Reflection.Metadata.Ecma335;
using System.Text.Json;
namespace Shogi.UI.Shared;
public class ShogiApi(HttpClient httpClient)
{
private readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
public async Task Register(string email, string password)
{
var response = await httpClient.PostAsJsonAsync(Relative("register"), new { email, password });
response.EnsureSuccessStatusCode();
}
public async Task LoginEventArgs(string email, string password)
{
var response = await httpClient.PostAsJsonAsync("login?useCookies=true", new { email, password });
response.EnsureSuccessStatusCode();
}
public async Task Logout()
{
var response = await httpClient.PutAsync(Relative("User/GuestLogout"), null);
response.EnsureSuccessStatusCode();
}
public async Task<Session?> GetSession(string name)
{
var response = await httpClient.GetAsync(Relative($"Sessions/{name}"));
if (response.IsSuccessStatusCode)
{
return (await response.Content.ReadFromJsonAsync<Session>(this.serializerOptions));
}
return null;
}
public async Task<SessionMetadata[]> GetAllSessionsMetadata()
{
var response = await httpClient.GetAsync(Relative("Sessions"));
if (response.IsSuccessStatusCode)
{
return (await response.Content.ReadFromJsonAsync<SessionMetadata[]>(this.serializerOptions))!;
}
return [];
}
/// <summary>
/// Returns false if the move was not accepted by the server.
/// </summary>
public async Task<bool> Move(Guid sessionName, MovePieceCommand command)
{
var response = await httpClient.PatchAsync(Relative($"Sessions/{sessionName}/Move"), JsonContent.Create(command));
return response.IsSuccessStatusCode;
}
public async Task<string?> PostSession()
{
var response = await httpClient.PostAsync(Relative("Sessions"), null);
var sessionId = response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : null;
return sessionId;
}
public Task<HttpResponseMessage> PatchJoinGame(string name)
{
return httpClient.PatchAsync(Relative($"Sessions/{name}/Join"), null);
}
public Task<HttpResponseMessage> DeleteSession(Guid sessionId)
{
return httpClient.DeleteAsync(Relative($"Sessions/{sessionId}"));
}
private static Uri Relative(string path) => new(path, UriKind.Relative);
}