jsonrpc.rs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. use async_trait::async_trait;
  2. use log::error;
  3. use serde_json::{json, Value};
  4. use darkfi::{
  5. rpc::{
  6. jsonrpc::{ErrorCode, JsonError, JsonRequest, JsonResponse, JsonResult},
  7. server::RequestHandler,
  8. },
  9. Error,
  10. };
  11. pub struct JsonRpcInterface {
  12. update_notifier: async_channel::Sender<()>,
  13. }
  14. #[async_trait]
  15. impl RequestHandler for JsonRpcInterface {
  16. async fn handle_request(&self, req: JsonRequest) -> JsonResult {
  17. if !req.params.is_array() {
  18. return JsonError::new(ErrorCode::InvalidParams, None, req.id).into()
  19. }
  20. let params = req.params.as_array().unwrap();
  21. let rep = match req.method.as_str() {
  22. Some("update") => self.update(req.id, params).await,
  23. Some(_) | None => return JsonError::new(ErrorCode::MethodNotFound, None, req.id).into(),
  24. };
  25. rep
  26. }
  27. }
  28. impl JsonRpcInterface {
  29. pub fn new(update_notifier: async_channel::Sender<()>) -> Self {
  30. Self { update_notifier }
  31. }
  32. // RPCAPI:
  33. // Update files in ~/darkwiki
  34. // --> {"jsonrpc": "2.0", "method": "update", "params": [], "id": 1}
  35. // <-- {"jsonrpc": "2.0", "result": true, "id": 1}
  36. async fn update(&self, id: Value, _params: &[Value]) -> JsonResult {
  37. let res = self.update_notifier.send(()).await.map_err(Error::from);
  38. if let Err(e) = res {
  39. error!("Failed to update: {}", e);
  40. return JsonError::new(ErrorCode::InternalError, None, id).into()
  41. }
  42. JsonResponse::new(json!(true), id).into()
  43. }
  44. }