87 lines
2.3 KiB
C#
87 lines
2.3 KiB
C#
namespace Bts.Websocket;
|
|
|
|
using bts.websocket_core;
|
|
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using System.Text.Json.Serialization;
|
|
|
|
public static class JsonRpcRequest {
|
|
public static JsonRpcRequest<T> Create<T>(JsonRpcId id, string method, T parameters) =>
|
|
new() {
|
|
Id = id,
|
|
Method = method,
|
|
Params = parameters
|
|
};
|
|
|
|
public static JsonRpcRequest<T> CreateNotification<T>(string method, T parameters) =>
|
|
new() {
|
|
Method = method,
|
|
Params = parameters
|
|
};
|
|
|
|
public static bool TryDeserialize(
|
|
WebsocketIncomingMessage message,
|
|
[NotNullWhen(true)]out JsonRpcRequest<JsonObject?>? result,
|
|
[NotNullWhen(false)]out string? error
|
|
) {
|
|
try {
|
|
result = JsonSerializer.Deserialize<JsonRpcRequest<JsonObject?>>(message.message_body)!;
|
|
error = null;
|
|
return true;
|
|
} catch (Exception ex) {
|
|
error = ex.ToString();
|
|
result = null;
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
|
|
public class JsonRpcRequest<T> {
|
|
[JsonPropertyName("method")]
|
|
public string? Method { get; set; }
|
|
|
|
[JsonPropertyName("params")]
|
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
|
[MaybeNull]
|
|
public T Params { get; set; }
|
|
|
|
[JsonPropertyName("jsonrpc")]
|
|
public string JsonRpc { get; set; } = "2.0";
|
|
|
|
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
|
[JsonPropertyName("id")]
|
|
public JsonRpcId? Id { get; set; }
|
|
|
|
[JsonIgnore]
|
|
public bool IsNotification =>
|
|
!Id.HasValue;
|
|
|
|
public string Serialize() =>
|
|
Serialize(JsonSerializerOptions.Default);
|
|
|
|
public string Serialize(JsonSerializerOptions opts) =>
|
|
JsonSerializer.Serialize(this, opts);
|
|
|
|
public bool SerializeSafe(
|
|
[NotNullWhen(true)]out string? result,
|
|
[NotNullWhen(false)]out Exception? error) =>
|
|
SerializeSafe(JsonSerializerOptions.Default, out result, out error);
|
|
|
|
public bool SerializeSafe(
|
|
JsonSerializerOptions opts,
|
|
[NotNullWhen(true)]out string? result,
|
|
[NotNullWhen(false)]out Exception? error) {
|
|
try {
|
|
result = JsonSerializer.Serialize(this, opts);
|
|
error = null;
|
|
return true;
|
|
} catch (Exception ex) {
|
|
error = ex;
|
|
result = null;
|
|
return false;
|
|
}
|
|
}
|
|
}
|