| 56 | } |
| 57 | |
| 58 | pub fn register<P, R, F, Fut>(&mut self, method: &'static str, handler: F) |
| 59 | where |
| 60 | P: DeserializeOwned + Send + 'static, |
| 61 | R: Serialize + Send + 'static, |
| 62 | F: Fn(P) -> Fut + Send + Sync + Clone + 'static, |
| 63 | Fut: Future<Output = Result<R, RpcError>> + Send + 'static, |
| 64 | { |
| 65 | let boxed: BoxedHandler = Box::new(move |_ctx, params: &[u8]| { |
| 66 | let handler = handler.clone(); |
| 67 | let params: Result<P, _> = serde_json::from_slice(params); |
| 68 | Box::pin(async move { |
| 69 | let params = params.map_err(|e| RpcError::invalid_params(e))?; |
| 70 | let result = handler(params).await?; |
| 71 | serde_json::to_value(&result).map_err(|_| RpcError::internal_error("parsing error")) |
| 72 | }) |
| 73 | }); |
| 74 | self.handlers.insert(method, boxed); |
| 75 | } |
| 76 | |
| 77 | pub fn register_with_context<P, R, F, Fut>(&mut self, method: &'static str, handler: F) |
| 78 | where |