forked from Linq2GraphQL/Linq2GraphQL.Client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphSubscriptionExecute.cs
More file actions
53 lines (45 loc) · 1.74 KB
/
GraphSubscriptionExecute.cs
File metadata and controls
53 lines (45 loc) · 1.74 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
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reactive.Linq;
namespace Linq2GraphQL.Client.Subscriptions;
public class GraphSubscriptionExecute<T, TResult> : GraphBaseExecute<T, TResult>
{
public GraphSubscriptionExecute(GraphClient client, OperationType operationType, QueryNode queryNode,
Expression<Func<T, TResult>> selector) : base(client, operationType, queryNode, selector) { }
public async Task<IObservable<TResult>> StartAsync()
{
var request = await GetRequestAsync();
if (string.IsNullOrWhiteSpace(client.SubscriptionUrl))
{
throw new Exception("Subscription url is not set");
}
if (client.SubscriptionProtocol == SubscriptionProtocol.ServerSentEvents)
{
var sseClient = new SSEClient(client, request);
#pragma warning disable CS4014
Task.Run(sseClient.Start);
#pragma warning restore CS4014
return sseClient.Subscription.SelectMany(json => SafeProcessMessage(json, request));
}
var wsClient = new WSClient(client, request);
await wsClient.Start();
return wsClient.Subscription.SelectMany(json => SafeProcessMessage(json, request));
}
private IEnumerable<TResult> SafeProcessMessage(string json, GraphQLRequest request)
{
if (string.IsNullOrWhiteSpace(json))
{
return Array.Empty<TResult>();
}
try
{
var result = queryExecutor.ProcessResponse(json, QueryNode.Name, request);
return new[] { ConvertResult(result) };
}
catch (Exception ex)
{
Debug.WriteLine($"Subscription message error: {ex.Message}");
return Array.Empty<TResult>();
}
}
}