Starts simplifying code interfaces to fetch sets

This commit is contained in:
Serraniel 2023-03-01 16:33:54 +01:00
parent 48209a130b
commit 863f708ed1
Signed by: Serraniel
GPG key ID: 3690B4E7364525D3

View file

@ -1,12 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Http.Json; using System.Net.Http.Json;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using System.Threading.Tasks; using System.Threading.Tasks;
using JpnCardsPokemonSdk.Client.Endpoints; using JpnCardsPokemonSdk.Api;
using JpnCardsPokemonSdk.Client.Responses; using JpnCardsPokemonSdk.Client.Responses;
namespace JpnCardsPokemonSdk.Client; namespace JpnCardsPokemonSdk.Client;
@ -35,6 +36,18 @@ public class ApiClient
new ProductHeaderValue("JpnCardsPokemonSdkCS", GetType().Assembly.GetName().Version?.ToString()))); new ProductHeaderValue("JpnCardsPokemonSdkCS", GetType().Assembly.GetName().Version?.ToString())));
} }
private async Task<T?> FetchInternalAsync<T>(string requestUri)
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
IncludeFields = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
return await _client.GetFromJsonAsync<T>(requestUri, options);
}
public async Task<TResponseType?> FetchDataAsync<TResponseType, TResponseGeneric>(string requestUri) public async Task<TResponseType?> FetchDataAsync<TResponseType, TResponseGeneric>(string requestUri)
where TResponseType : IApiResponse<TResponseGeneric>, new() where TResponseType : IApiResponse<TResponseGeneric>, new()
{ {
@ -62,6 +75,29 @@ public class ApiClient
return result; return result;
} }
private string SetQuery(string? filter)
{
var result = "set";
return !string.IsNullOrEmpty(filter) ? $"{result}/{filter.TrimStart('/')}" : result;
}
public async Task<IEnumerable<Set>> FetchSetsAsync()
{
return await FetchInternalAsync<IEnumerable<Set>>(SetQuery(null)) ?? Enumerable.Empty<Set>();
}
public async Task<Set?> FetchSetById(int id)
{
return await FetchInternalAsync<Set>(SetQuery(id.ToString()));
}
public async Task<Set?> FetchSetByUuid(int uuid)
{
return await FetchInternalAsync<Set>(SetQuery("uuid/" + uuid));
}
/*
public async Task<EnumerableApiResponse<T>?> FetchDataAsync<T>(string? query = null, int page = 1) public async Task<EnumerableApiResponse<T>?> FetchDataAsync<T>(string? query = null, int page = 1)
where T : EndpointObject where T : EndpointObject
{ {
@ -82,5 +118,5 @@ public class ApiClient
var endpoint = EndpointFactory.GetApiEndpoint<T>(); var endpoint = EndpointFactory.GetApiEndpoint<T>();
return await FetchDataAsync<SingleApiResponse<T>, T>($"{endpoint.ApiUri()}/uuid={uuid}"); return await FetchDataAsync<SingleApiResponse<T>, T>($"{endpoint.ApiUri()}/uuid={uuid}");
} }*/
} }