Debian Codegraph @

modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs

raw symbols SCIP
1 using System.Collections.Generic;
2 using System.Threading.Tasks;
3 using GodotTools.IdeMessaging.Requests;
4 using Newtonsoft.Json;
5
6 namespace GodotTools.IdeMessaging
7 {
8 // ReSharper disable once UnusedType.Global
9 public abstract class ClientMessageHandler : IMessageHandler
10 {
11 private readonly Dictionary<string, Peer.RequestHandler> requestHandlers;
12
13 protected ClientMessageHandler()
14 {
15 requestHandlers = InitializeRequestHandlers();
16 }
17
18 public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
19 {
20 if (!requestHandlers.TryGetValue(id, out var handler))
21 {
22 logger.LogError($"Received unknown request: {id}");
23 return new MessageContent(MessageStatus.RequestNotSupported, "null");
24 }
25
26 try
27 {
28 var response = await handler(peer, content);
29 return new MessageContent(response.Status, JsonConvert.SerializeObject(response));
30 }
31 catch (JsonException)
32 {
33 logger.LogError($"Received request with invalid body: {id}");
34 return new MessageContent(MessageStatus.InvalidRequestBody, "null");
35 }
36 }
37
38 private Dictionary<string, Peer.RequestHandler> InitializeRequestHandlers()
39 {
40 return new Dictionary<string, Peer.RequestHandler>
41 {
42 [OpenFileRequest.Id] = async (peer, content) =>
43 {
44 var request = JsonConvert.DeserializeObject<OpenFileRequest>(content.Body);
45 return await HandleOpenFile(request!);
46 }
47 };
48 }
49
50 protected abstract Task<Response> HandleOpenFile(OpenFileRequest request);
51 }
52 }