Skip to content

Commit d0cece9

Browse files
author
Navid Kabir
authored
Merge pull request NavidK0#37 from Sewdn/master
2 parents c5e7634 + c0e3997 commit d0cece9

File tree

2 files changed

+65
-10
lines changed

2 files changed

+65
-10
lines changed

Runtime/SimpleGraphQL/GraphQLClient.cs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,19 @@ public void RegisterListener(Action<string> listener)
112112
HttpUtils.SubscriptionDataReceived += listener;
113113
}
114114

115+
public void RegisterListener(string id, Action<string> listener)
116+
{
117+
if(!HttpUtils.SubscriptionDataReceivedPerChannel.ContainsKey(id)) {
118+
HttpUtils.SubscriptionDataReceivedPerChannel[id] = null;
119+
}
120+
HttpUtils.SubscriptionDataReceivedPerChannel[id] += listener;
121+
}
122+
123+
public void RegisterListener(Request request, Action<string> listener)
124+
{
125+
RegisterListener(request.Query.ToMurmur2Hash().ToString(), listener);
126+
}
127+
115128
/// <summary>
116129
/// Unregisters a listener for subscriptions.
117130
/// </summary>
@@ -121,6 +134,18 @@ public void UnregisterListener(Action<string> listener)
121134
HttpUtils.SubscriptionDataReceived -= listener;
122135
}
123136

137+
public void UnregisterListener(string id, Action<string> listener)
138+
{
139+
if(HttpUtils.SubscriptionDataReceivedPerChannel.ContainsKey(id)) {
140+
HttpUtils.SubscriptionDataReceivedPerChannel[id] -= listener;
141+
}
142+
}
143+
144+
public void UnregisterListener(Request request, Action<string> listener)
145+
{
146+
UnregisterListener(request.Query.ToMurmur2Hash().ToString(), listener);
147+
}
148+
124149
/// <summary>
125150
/// Subscribe to a query in GraphQL.
126151
/// </summary>

Runtime/SimpleGraphQL/HttpUtils.cs

Lines changed: 40 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@ public static class HttpUtils
2121
/// Called when the websocket receives subscription data.
2222
/// </summary>
2323
public static event Action<string> SubscriptionDataReceived;
24+
public static Dictionary<string, Action<string>> SubscriptionDataReceivedPerChannel;
2425

2526
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
2627
public static void PreInit()
2728
{
2829
_webSocket?.Dispose();
2930
SubscriptionDataReceived = null;
31+
SubscriptionDataReceivedPerChannel = new Dictionary<string, Action<string>>();
3032
}
3133

3234
/// <summary>
@@ -138,10 +140,23 @@ public static async Task WebSocketConnect(
138140
_webSocket = new ClientWebSocket();
139141
_webSocket.Options.AddSubProtocol(protocol);
140142

141-
if (authToken != null)
142-
_webSocket.Options.SetRequestHeader("Authorization", $"{authScheme} {authToken}");
143+
var payload = new Dictionary<string, string>();
144+
145+
if(protocol == "graphql-transport-ws") {
146+
payload["content-type"] = "application/json";
147+
} else {
148+
_webSocket.Options.SetRequestHeader("Content-Type", "application/json");
149+
}
150+
151+
if (authToken != null) {
152+
if(protocol == "graphql-transport-ws") {
153+
// set Authorization as payload
154+
payload["Authorization"] = $"{authScheme} {authToken}";
155+
} else {
156+
_webSocket.Options.SetRequestHeader("Authorization", $"{authScheme} {authToken}");
157+
}
158+
}
143159

144-
_webSocket.Options.SetRequestHeader("Content-Type", "application/json");
145160

146161
if (headers != null)
147162
{
@@ -156,12 +171,23 @@ public static async Task WebSocketConnect(
156171
Debug.Log("Websocket is connecting");
157172
await _webSocket.ConnectAsync(uri, CancellationToken.None);
158173

174+
var json = JsonConvert.SerializeObject(
175+
new
176+
{
177+
type = "connection_init",
178+
payload = payload
179+
},
180+
Formatting.None,
181+
new JsonSerializerSettings
182+
{
183+
NullValueHandling = NullValueHandling.Ignore
184+
}
185+
);
186+
159187
Debug.Log("Websocket is starting");
160188
// Initialize the socket at the server side
161189
await _webSocket.SendAsync(
162-
new ArraySegment<byte>(
163-
Encoding.UTF8.GetBytes(@"{""type"":""connection_init"",""payload"": {}}")
164-
),
190+
new ArraySegment<byte>(Encoding.UTF8.GetBytes(json)),
165191
WebSocketMessageType.Text,
166192
true,
167193
CancellationToken.None
@@ -210,7 +236,7 @@ public static async Task<bool> WebSocketSubscribe(string id, Request request)
210236
new
211237
{
212238
id,
213-
type = "start",
239+
type = _webSocket.SubProtocol == "graphql-transport-ws" ? "subscribe" : "start",
214240
payload = new
215241
{
216242
query = request.Query,
@@ -248,8 +274,10 @@ public static async Task WebSocketUnsubscribe(string id)
248274
return;
249275
}
250276

277+
var type = _webSocket.SubProtocol == "graphql-transport-ws" ? "complete" : "stop";
278+
251279
await _webSocket.SendAsync(
252-
new ArraySegment<byte>(Encoding.UTF8.GetBytes($@"{{""type"":""stop"",""id"":""{id}""}}")),
280+
new ArraySegment<byte>(Encoding.UTF8.GetBytes($@"{{""type"":""{type}"",""id"":""{id}""}}")),
253281
WebSocketMessageType.Text,
254282
true,
255283
CancellationToken.None
@@ -292,6 +320,7 @@ private static async void WebSocketUpdate()
292320
}
293321

294322
var msgType = (string)jsonObj["type"];
323+
var id = (string)jsonObj["id"];
295324
switch (msgType)
296325
{
297326
case "connection_error":
@@ -300,7 +329,7 @@ private static async void WebSocketUpdate()
300329
}
301330
case "connection_ack":
302331
{
303-
Debug.Log("Websocket connection acknowledged.");
332+
Debug.Log($"Websocket connection acknowledged ({id}).");
304333
continue;
305334
}
306335
case "data":
@@ -311,6 +340,7 @@ private static async void WebSocketUpdate()
311340
if (jToken != null)
312341
{
313342
SubscriptionDataReceived?.Invoke(jToken.ToString());
343+
SubscriptionDataReceivedPerChannel?[id]?.Invoke(jToken.ToString());
314344
}
315345

316346
continue;
@@ -349,4 +379,4 @@ await _webSocket.SendAsync(
349379
}
350380
}
351381
}
352-
}
382+
}

0 commit comments

Comments
 (0)