From 2ee34b432e7652a34ee64a706b5ebc1bce867dce Mon Sep 17 00:00:00 2001 From: hozan23 Date: Mon, 20 Nov 2023 22:19:02 +0300 Subject: jsonrpc: move RPCService to separate module --- jsonrpc/src/service.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 jsonrpc/src/service.rs (limited to 'jsonrpc/src/service.rs') diff --git a/jsonrpc/src/service.rs b/jsonrpc/src/service.rs new file mode 100644 index 0000000..f0e2828 --- /dev/null +++ b/jsonrpc/src/service.rs @@ -0,0 +1,60 @@ +use std::{future::Future, pin::Pin}; + +use crate::Result; + +/// Represents the RPC method +pub type RPCMethod<'a> = Box RPCMethodOutput<'a> + Send + 'a>; +type RPCMethodOutput<'a> = + Pin> + Send + Sync + 'a>>; + +/// Defines the interface for an RPC service. +pub trait RPCService: Sync + Send { + fn get_method<'a>(&'a self, name: &'a str) -> Option; + fn name(&self) -> String; +} + +/// Implements the `RPCService` trait for a provided type. +/// +/// # Example +/// +/// ``` +/// use serde_json::Value; +/// +/// use karyons_jsonrpc::{JsonRPCError, register_service}; +/// +/// struct Hello {} +/// +/// impl Hello { +/// async fn say_hello(&self, params: Value) -> Result { +/// Ok(serde_json::json!("hello!")) +/// } +/// } +/// +/// register_service!(Hello, say_hello); +/// +/// ``` +#[macro_export] +macro_rules! register_service { + ($t:ty, $($m:ident),*) => { + impl karyons_jsonrpc::RPCService for $t { + fn get_method<'a>( + &'a self, + name: &'a str + ) -> Option { + match name { + $( + stringify!($m) => { + Some(Box::new(move |params: serde_json::Value| Box::pin(self.$m(params)))) + } + )* + _ => None, + } + + + } + fn name(&self) -> String{ + stringify!($t).to_string() + } + } + }; +} -- cgit v1.2.3