Files
bodyshop-uploader/BodyshopUploader/Utils/GraphQL.cs
2021-05-26 10:30:52 -07:00

66 lines
2.3 KiB
C#

using GraphQL.Client;
using GraphQL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GraphQL.Client.Http;
using GraphQL.Client.Serializer.Newtonsoft;
namespace BodyshopPartner.Utils
{
public static class GraphQL
{
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
public static GraphQLHttpClient CreateGQLClient()
{
var graphQLClient = new GraphQLHttpClient(AppMetaData.graphQlEndpoint, new NewtonsoftJsonSerializer());
graphQLClient.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + Utils.Auth.authlink.FirebaseToken);
return graphQLClient;
}
public static async Task<dynamic> ExecuteQuery(GraphQLRequest r, bool lastTry = false)
{
using (var g = Utils.GraphQL.CreateGQLClient())
{
logger.Trace("Firing a GQL Query!");
logger.Trace("Firing GQL Query: {0} {1}", r.Query.ToString(), r.Variables);
var graphQLResponse = await g.SendQueryAsync<dynamic>(r);
if (graphQLResponse.Errors == null)
{
//logger.Trace("GQL Response: {0}", graphQLResponse.Data);
return graphQLResponse.Data;
}
else
{
string exceptionString = "";
bool jwtExpired = false;
logger.Error("Error executing query.");
Array.ForEach(graphQLResponse.Errors, x =>
{
logger.Error("Graphql Error: " + x.Message);
if (x.Message.Contains("JWTExpired"))
{
jwtExpired = true;
};
exceptionString = exceptionString + x + ";";
});
if (jwtExpired && !lastTry) { await Utils.Auth.Refresh();
return (ExecuteQuery(r, true));
}
else
{
logger.Error("---------------------");
throw new Exception(exceptionString);
}
}
}
}
}
}