Files
spark/src/client/spark_websocket/Core/WebsocketRequest.cs
T

77 lines
2.6 KiB
C#

using Newtonsoft.Json.Linq;
using System.Diagnostics.CodeAnalysis;
namespace bts.websocket_core {
//Holds request id, request type, and request parameters
public class WebsocketRequest {
public enum REQUEST_TYPES {
SUBSCRIBE = 1,
UNSUBSCRIBE_ALL,
UNSUBSCRIBE,
ENTER_ORDER,
DELETE_ORDER,
UPDATE_ORDER,
SET_PRECOMPUTED_THEOS,
DELETE,
PATCH,
UNKOWN = 0
}
public readonly WebsocketRequestID id;
public readonly WebsocketClientID client_id;
public readonly JObject parameters;
public readonly REQUEST_TYPES type;
private static bool TryParseJson(string json, out string _message_id, out REQUEST_TYPES type, [NotNullWhen(true)] out JObject? para, [NotNullWhen(false)] out string message) {
para = null;
type = REQUEST_TYPES.UNKOWN;
JObject request;
_message_id = "missing";
try {
request = JObject.Parse(json);
} catch (Newtonsoft.Json.JsonReaderException ex) {
message = $"Incorrect Json: {ex.Path}";
return false;
}
if (!WebsocketJsonParsers.TryParse(request, "id", out string? message_id, out message)
|| message_id == null) {
return false;
}
_message_id = message_id ?? "missing";
if (!WebsocketJsonParsers.TryParse(request, "method", out REQUEST_TYPES? rt, out message)) {
return false;
}
type = rt ?? REQUEST_TYPES.UNKOWN;
para = (JObject?)request["params"] ?? new JObject();
return true;
}
public static bool TryGetWebSocketRequest(WebsocketClientID cid, string json, out IUniqueID id, [NotNullWhen(true)] out WebsocketRequest? wr, out string message) {
JObject? jobj;
REQUEST_TYPES rt;
if (TryParseJson(json, out string _message_id, out rt, out jobj, out message)) {
wr = new WebsocketRequest(cid, new WebsocketRequestID(_message_id), jobj, rt);
id = wr.id;
return true;
}
id = new UniqueID(_message_id);
wr = null;
return false;
}
private WebsocketRequest(
WebsocketClientID _cid,
WebsocketRequestID _id,
JObject jobj,
REQUEST_TYPES rt
) {
(client_id, id, parameters, type) = (_cid, _id, jobj, rt);
}
public WebsocketRequest(WebsocketRequest other, JObject para) {
client_id = other.client_id;
id = other.id;
(parameters, type) = (para, other.type);
}
}
}