-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGraphClient.cs
More file actions
77 lines (63 loc) · 2.41 KB
/
GraphClient.cs
File metadata and controls
77 lines (63 loc) · 2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using System.Text.Json;
using System.Text.Json.Serialization;
using Linq2GraphQL.Client.Schema;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace Linq2GraphQL.Client;
public class GraphClient
{
private readonly IMemoryCache cache;
private readonly IOptions<GraphClientOptions> options;
public GraphClient(HttpClient httpClient, IOptions<GraphClientOptions> options, IServiceProvider provider)
{
this.options = options;
if (options.Value.UseSafeMode)
{
cache = provider.GetRequiredService<IMemoryCache>();
}
HttpClient = httpClient;
SerializerOptions = new()
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = { }
};
SubscriptionUrl = GetSubscriptionUrl();
}
public string SubscriptionUrl { get; }
public SubscriptionProtocol SubscriptionProtocol => options.Value.SubscriptionProtocol;
public HttpClient HttpClient { get; }
public JsonSerializerOptions SerializerOptions { get; }
private string GetSubscriptionUrl()
{
var baseUrl = HttpClient?.BaseAddress.ToString();
if (string.IsNullOrWhiteSpace(baseUrl))
{
throw new ArgumentNullException("HttpClient BaseAddress must be set");
}
if (SubscriptionProtocol == SubscriptionProtocol.ServerSentEvents)
{
return baseUrl;
}
return HttpClient.BaseAddress.Scheme switch
{
"http" => new UriBuilder(HttpClient.BaseAddress) { Scheme = "ws" }.Uri.ToString(),
"https" => new UriBuilder(HttpClient.BaseAddress) { Scheme = "wss" }.Uri.ToString(),
_ => throw new Exception($"BaseAddress Scheme {HttpClient.BaseAddress.Scheme} is unknown")
};
}
public async Task<GraphQLSchema> GetSchemaForSafeModeAsync()
{
if (!options.Value.UseSafeMode)
{
return null;
}
var cackeKey = "Linq2GraphQL_Schema:" + HttpClient.BaseAddress;
return await cache.GetOrCreateAsync(cackeKey, async entry =>
{
var executor = new QueryExecutor<GraphQLSchema>(this);
var graphRequest = new GraphQLRequest { Query = Helpers.SchemaQuery };
return await executor.ExecuteRequestAsync("__schema", graphRequest);
});
}
}