From c7a6ff56847d79459ec7fb81fde55e06c8fefd0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20LAVERGNE?= Date: Sun, 16 Jun 2024 19:11:59 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9E=95=20IGDB=20base=20client=20to=20query?= =?UTF-8?q?=20the=20API=20&=20return=20the=20response=20(async=20func)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Sources/GameAtlas/Models/API/IGDBClient.cs | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Sources/GameAtlas/Models/API/IGDBClient.cs diff --git a/Sources/GameAtlas/Models/API/IGDBClient.cs b/Sources/GameAtlas/Models/API/IGDBClient.cs new file mode 100644 index 0000000..a3884e1 --- /dev/null +++ b/Sources/GameAtlas/Models/API/IGDBClient.cs @@ -0,0 +1,47 @@ +using Microsoft.Extensions.Options; +using System.Diagnostics; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Runtime; +using System.Text.Json; +using System.Threading.Tasks; + +namespace Models.API +{ + public class IGDBClient + { + private readonly HttpClient _httpClient; + private readonly AuthService _authService; + private readonly IGDBSettings _settings; + + public IGDBClient(HttpClient httpClient, AuthService authService, IGDBSettings settings) + { + _httpClient = httpClient; + _authService = authService; + _settings = settings; + } + + public async Task GetGamesAsync() + { + var authResponse = await _authService.GetAccessTokenAsync(_settings.ClientId, _settings.ClientSecret); + _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResponse.AccessToken); + _httpClient.DefaultRequestHeaders.Add("Client-ID", _settings.ClientId); + + var request = new HttpRequestMessage(HttpMethod.Post, "https://api.igdb.com/v4/games"); + request.Content = new StringContent("fields name,genres.name; limit 10;", System.Text.Encoding.UTF8, "application/json"); + + var response = await _httpClient.SendAsync(request); + + if (!response.IsSuccessStatusCode) + { + var errorContent = await response.Content.ReadAsStringAsync(); + Console.WriteLine($"Request error: {response.StatusCode}, Content: {errorContent}"); + throw new HttpRequestException($"Response status code: {response.StatusCode} ({errorContent})"); + } + + var responseContent = await response.Content.ReadAsStringAsync(); + return responseContent; + } + } +}