Files
bodyshop-uploader/BodyshopUploader/Utils/GraphQL.cs
2022-08-30 15:06:44 -07:00

105 lines
3.9 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;
using System.Net.Http;
using Newtonsoft;
using Newtonsoft.Json.Linq;
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 content = new content("grant_type=password&username=username&password=password");
//content.Headers.Add("Content-Type", "application/json");
dynamic postData = new JObject();
postData.imexshopid = AppMetaData.ActiveShopName;
postData.operationName = r.Query.ToString();
postData.dbevent = true;
postData.user = AppMetaData.user;
postData.source = "Partner";
var httpClient = new HttpClient();
var content = new StringContent(postData.ToString(), Encoding.UTF8, "application/json");
try
{
// httpClient.PostAsync("https://api.imex.online/ioevent", content);
}
catch (Exception ex)
{
logger.Error(ex, "Unable to post to IOEVENT.");
}
try
{
var graphQLResponse = await g.SendQueryAsync<dynamic>(r);
logger.Debug("Graphql response:");
logger.Debug("Data: " + graphQLResponse.Data);
logger.Debug("Error: " + graphQLResponse.Errors);
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);
}
}
}
catch (Exception ex)
{
logger.Error("Error firing GQL query.");
logger.Error(ex);
throw ex;
}
}
}
}
}