summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/ClientMessageHandler.cs
blob: 64bcfd824c4a0c296fa2ed2834daad47acceaba3 (plain)
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
using System.Collections.Generic;
using System.Threading.Tasks;
using GodotTools.IdeMessaging.Requests;
using Newtonsoft.Json;

namespace GodotTools.IdeMessaging
{
    // ReSharper disable once UnusedType.Global
    public abstract class ClientMessageHandler : IMessageHandler
    {
        private readonly Dictionary<string, Peer.RequestHandler> requestHandlers;

        protected ClientMessageHandler()
        {
            requestHandlers = InitializeRequestHandlers();
        }

        public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
        {
            if (!requestHandlers.TryGetValue(id, out var handler))
            {
                logger.LogError($"Received unknown request: {id}");
                return new MessageContent(MessageStatus.RequestNotSupported, "null");
            }

            try
            {
                var response = await handler(peer, content);
                return new MessageContent(response.Status, JsonConvert.SerializeObject(response));
            }
            catch (JsonException)
            {
                logger.LogError($"Received request with invalid body: {id}");
                return new MessageContent(MessageStatus.InvalidRequestBody, "null");
            }
        }

        private Dictionary<string, Peer.RequestHandler> InitializeRequestHandlers()
        {
            return new Dictionary<string, Peer.RequestHandler>
            {
                [OpenFileRequest.Id] = async (peer, content) =>
                {
                    var request = JsonConvert.DeserializeObject<OpenFileRequest>(content.Body);
                    return await HandleOpenFile(request);
                }
            };
        }

        protected abstract Task<Response> HandleOpenFile(OpenFileRequest request);
    }
}