Skip to content

Commit

Permalink
Add a method to RpcModule that transforms the module into a `RpcModul…
Browse files Browse the repository at this point in the history
…e<()>`, i.e. removes the context. (#660)

* Add a method to RpcModule, `decontextualize`, that transforms the module into a `RpcModule<()>`, i.e. removes the context.

* Merging a module with an empty module cannot fail

* fmt

* Address grumbles

* Cleanup macro

* Update core/src/server/rpc_module.rs

Co-authored-by: Maciej Hirsz <1096222+maciejhirsz@users.noreply.github.com>

Co-authored-by: Maciej Hirsz <1096222+maciejhirsz@users.noreply.github.com>
  • Loading branch information
dvdplm and maciejhirsz committed Jan 21, 2022
1 parent 9bd2127 commit c0f343d
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
7 changes: 7 additions & 0 deletions core/src/server/rpc_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,13 @@ impl<Context> RpcModule<Context> {
pub fn new(ctx: Context) -> Self {
Self { ctx: Arc::new(ctx), methods: Default::default() }
}

/// Transform a module into an `RpcModule<()>` (unit context).
pub fn remove_context(self) -> RpcModule<()> {
let mut module = RpcModule::new(());
module.methods = self.methods;
module
}
}

impl<Context> From<RpcModule<Context>> for Methods {
Expand Down
2 changes: 1 addition & 1 deletion examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,4 @@ path = "core_client.rs"

[[example]]
name = "cors_server"
path = "cors_server.rs"
path = "cors_server.rs"
16 changes: 16 additions & 0 deletions tests/tests/rpc_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ use jsonrpsee::core::server::rpc_module::*;
use jsonrpsee::types::{EmptyParams, Params};
use serde::{Deserialize, Serialize};

// Helper macro to assert that a binding is of a specific type.
macro_rules! assert_type {
( $ty:ty, $expected:expr $(,)?) => {{
fn assert_type<Expected>(_expected: &Expected) {}
assert_type::<$ty>($expected)
}};
}

#[test]
fn rpc_modules_with_different_contexts_can_be_merged() {
let cx = Vec::<u8>::new();
Expand All @@ -45,6 +53,14 @@ fn rpc_modules_with_different_contexts_can_be_merged() {
assert!(mod1.method("bla with String context").is_some());
}

#[test]
fn flatten_rpc_modules() {
let mod1 = RpcModule::new(String::new());
assert_type!(RpcModule<String>, &mod1);
let unit_mod = mod1.remove_context();
assert_type!(RpcModule<()>, &unit_mod);
}

#[test]
fn rpc_context_modules_can_register_subscriptions() {
let cx = ();
Expand Down

0 comments on commit c0f343d

Please sign in to comment.