beatsaber-scoretracker/Mod/API/Request.cs
Liam 7b560075ba
Some checks failed
Deploy API / docker (17, 3.8.5) (push) Failing after 35s
Release Mod / Build (push) Successful in 30s
mod: cleanup auth
2024-08-15 18:22:16 +01:00

53 lines
1.9 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ScoreTracker.API
{
internal class Request
{
internal static readonly HttpClient HttpClient = new HttpClient();
/// <summary>
/// Persist the given headers for all future requests
/// </summary>
/// <param name="headers">the headers to persist</param>
public static void PersistHeaders(Dictionary<string, string> headers)
{
HttpClient.DefaultRequestHeaders.Clear(); // Clear existing headers
foreach (var header in headers)
{
HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
/// <summary>
/// Create a POST request to the given URL with the given data
/// </summary>
/// <param name="url">the url to post to</param>
/// <param name="data">the data to post</param>
/// <param name="checkAuth">whether to check for authentication</param>
/// <returns>the task</returns>
public static async Task<HttpResponseMessage> PostJsonAsync(string url, Dictionary<object, object> json, bool checkAuth = true)
{
if (checkAuth)
{
var signinResponse = await Authentication.ValidateAndSignIn();
if (!signinResponse.Success)
{
throw new Exception($"Failed to log in: {signinResponse.Response}");
}
}
var jsonString = JsonConvert.SerializeObject(json, Formatting.None);
var content = new StringContent(jsonString, Encoding.UTF8, "application/json");
// Send the POST request
var response = await HttpClient.PostAsync(url, content);
return response;
}
}
}