Macro impl_patch

Source
macro_rules! impl_patch {
    ($name:ident, $patch_json:ty, $get_json:ty, $url:expr) => { ... };
}
Expand description

UI macro: implements a method to send a PATCH request.

Given a name, this macro implements a patch_name method that sends a PATCH request to a url. The response of the PATCH is then parsed as JSON, and the resulting Rust value is returned.

The patch method signature is async fn patch_name(&self, json: &$request_json) -> Result<$get_json, RequestError>.

ยงExample

use maia_wasm::{impl_patch, ui::request::ignore_request_failed};
use serde::{Deserialize, Serialize};
use std::rc::Rc;
use wasm_bindgen::JsValue;
use web_sys::Window;

// An object defined by a REST API. This corresponds to the GET method.
#[derive(Debug, Serialize, Deserialize)]
struct MyObject {
    my_value: u64,
}

// An object defined by a REST API. This corresponds to the PATCH method.
#[derive(Debug, Serialize, Deserialize)]
struct PatchMyObject {
    #[serde(skip_serializing_if = "Option::is_none")]
    my_value: Option<u64>,
}

#[derive(Clone)]
struct Ui {
    window: Rc<Window>,
}

impl Ui {
    fn new(window: Rc<Window>) -> Ui {
        Ui { window }
    }

    // it is necessary to define an alert method like this
    // to show errors to the user
    fn alert(&self, message: &str) -> Result<(), JsValue> {
        self.window.alert_with_message(message);
        Ok(())
    }

    impl_patch!(my_object, PatchMyObject, MyObject, "/my_object");
}

async fn example() -> Result<(), JsValue> {
    let (window, _) = maia_wasm::get_window_and_document()?;
    let ui = Ui::new(Rc::clone(&window));

    let patch = PatchMyObject { my_value: Some(42) };
    // server errors are already handled by patch_my_object by calling
    // Ui::alert, so we can ignore them here.
    if let Some(result) = ignore_request_failed(ui.patch_my_object(&patch).await)? {
        window.alert_with_message(&format!("request result: {result:?}"));
    }

    Ok(())
}