82 lines
2.3 KiB
Rust
Raw Normal View History

extern crate futures;
2018-08-18 17:20:42 -04:00
extern crate js_sys;
extern crate wasm_bindgen;
2018-08-18 17:20:42 -04:00
extern crate wasm_bindgen_futures;
extern crate web_sys;
2018-08-18 17:20:42 -04:00
#[macro_use]
extern crate serde_derive;
use futures::{future, Future};
use js_sys::Promise;
2018-08-18 17:20:42 -04:00
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::future_to_promise;
use wasm_bindgen_futures::JsFuture;
use web_sys::{Request, RequestInit, RequestMode, Response, Window};
2018-08-18 17:20:42 -04:00
/// 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
2018-08-18 17:20:42 -04:00
#[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 fn run() -> Promise {
let mut opts = RequestInit::new();
opts.method("GET");
opts.mode(RequestMode::Cors);
2018-08-18 17:20:42 -04:00
let request = Request::new_with_str_and_init(
"https://api.github.com/repos/rustwasm/wasm-bindgen/branches/master",
&opts,
).unwrap();
2018-08-18 17:20:42 -04:00
request.headers()
.set("Accept", "application/vnd.github.v3+json")
.unwrap();
2018-08-18 17:20:42 -04:00
let request_promise = Window::fetch_with_request(&request);
2018-08-18 17:20:42 -04:00
let future = JsFuture::from(request_promise)
.and_then(|resp_value| {
// `resp_value` is a `Response` object.
assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();
resp.json()
}).and_then(|json_value: Promise| {
// Convert this other `Promise` into a rust `Future`.
JsFuture::from(json_value)
}).and_then(|json| {
// Use serde to parse the JSON into a struct.
let branch_info: Branch = json.into_serde().unwrap();
2018-08-18 17:20:42 -04:00
// Send the `Branch` struct back to JS as an `Object`.
future::ok(JsValue::from_serde(&branch_info).unwrap())
});
2018-08-18 17:20:42 -04:00
// Convert this Rust `Future` back into a JS `Promise`.
future_to_promise(future)
2018-08-18 17:20:42 -04:00
}