Add error to JsValue conversion and example (#691)

This commit is contained in:
John Gallagher
2019-10-30 16:30:32 -04:00
committed by Sean McArthur
parent 57300edbc4
commit 43f2ff083c
9 changed files with 6224 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
use serde::{Deserialize, Serialize};
use wasm_bindgen::prelude::*;
// NOTE: This test is a clone of https://github.com/rustwasm/wasm-bindgen/blob/master/examples/fetch/src/lib.rs
// but uses Reqwest instead of the web_sys fetch api directly
/// A struct to hold some data from the github Branch API.
///
/// Note how we don't have to define every member -- serde will ignore extra
/// data when deserializing
#[derive(Debug, Serialize, Deserialize)]
pub struct Branch {
pub name: String,
pub commit: Commit,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Commit {
pub sha: String,
pub commit: CommitDetails,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CommitDetails {
pub author: Signature,
pub committer: Signature,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Signature {
pub name: String,
pub email: String,
}
#[wasm_bindgen]
pub async fn run() -> Result<JsValue, JsValue> {
let res = reqwest::Client::new()
.get("https://api.github.com/repos/rustwasm/wasm-bindgen/branches/master")
.send()
.await?;
let text = res.text().await?;
let branch_info: Branch = serde_json::from_str(&text).unwrap();
Ok(JsValue::from_serde(&branch_info).unwrap())
}