[WebAssembly] Rust 和 Wasm 的融合,使用 yew 构建 web 前端(5)- 构建 HTTP 请求、与外部服务器通信的两种方法
💥 内容涉及著作权,均归属作者本人。若非作者注明,默认欢迎转载:请注明出处,及相关链接。
Summary: 《Rust 和 Wasm 的融合,使用 yew 构建 WebAssembly 标准的 web 前端》系列文章第五部分:在 yew 开发的 wasm 前端应用中,与外部服务器进行数据交互时,直接使用 web-sys 库,比较方便灵活,并且较易拓展,已经可以满足开发。但在 yew 中,还有更易用的封装 FetchService,FetchService 封装了 web-sys 和 stdweb 两个库。对于请求的构建、响应的结果,也都做了一致封装,使用起来更为精简。如果你的 yew 项目中,除了 web-sys 之外,也希望使用 stdweb,那么 FetchService 则更为适合。
Topics: rust graphql webassembly wasm yew
在系列文章第四部分《获取 GraphQL 数据并解析 》中,我们已经与 GraphQL 服务后端进行了数据交互,获取 GraphQL 数据并解析。其中,我们直接使用的是 web-sys
库,需要获取当前的 window
对象,通过 window
对象的 Fetch API
,对请求进行分发。
直接使用 web-sys
库,比较方便灵活,并且较易拓展,已经可以满足开发。但在 yew
中,还有更易用的封装 FetchService
,FetchService
封装了 web-sys
和 stdweb
两个库。对于请求的构建、响应的结果,也都做了一致封装,使用起来更为精简。如果你的 yew 项目中,除了 web-sys
之外,也希望使用 stdweb
,那么 FetchService
则更为适合。
需要注意的是:因为
stdweb
仓库很久没有更新和改进了,所以 yew 将会在下个版本 0.19 中,移除对stdweb
的支持。stdweb
作为先行者,是一个非常优秀的库。
使用 web-sys
我们首先回忆一下前文中使用 web-sys
库获取 GraphQL 数据并解析的方法和过程。
构建请求
本文中,笔者使用的示例为构建一个 GraphQL 请求。相比于其它非 GraphQL 请求,如仅获取数据的 REST API,稍显复杂一些。如果你未使用或者不熟悉 GraphQL,直接忽略调 GraphQL 查询体构建部分即可,其它部分的请求构建,完全一致。
构造 GraphQL 请求的部分,主要是使用 graphql-client
库构造查询体 QueryBody<Variables>
。我们已经在《使用 handlebars、rhai、graphql 开发 Rust web 前端》,以及《Rust 和 Wasm 的融合,使用 yew 构建 web 前端》中多次提及,如果有所遗忘请参阅文章。此处笔者不再赘述,直接附上代码。
#[derive(GraphQLQuery)]
#[graphql(
...
)]
struct AllUsers;
async fn fetch_users() -> Result<Vec<Value>, FetchError> {
...
let build_query = AllUsers::build_query(all_users::Variables {
token: token.to_string(),
});
let query = serde_json::json!(build_query);
let mut req_opts = RequestInit::new();
req_opts.method("POST");
req_opts.body(Some(&JsValue::from_str(&query.to_string())));
let request = Request::new_with_str_and_init(&gql_uri(), &req_opts)?;
...
分发请求
构建 yew 的window
对象后,通过 window
对象的 Fetch API
,对请求进行分发。返回的结果类型为 JsValue
,通过动态的强制转换方法 dyn_into
将其转换为 web-sys
的 Reponse
类型。
let window = yew::utils::window();
let resp_value =
JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap();
另外,对于 Fetch API
,我们还需要实现 FetchError
结构体,以及特质(trait)From<JsValue>
。
#[derive(Debug, Clone, PartialEq)]
pub struct FetchError {
err: JsValue,
}
impl From<JsValue> for FetchError {
fn from(value: JsValue) -> Self {
Self { err: value }
}
}
数据解析
最后,结合自己的业务逻辑,再通过一系列类型转换,如文本、数组等,使其成为我们可以渲染到页面的数据。
let resp_text = JsFuture::from(resp.text()?).await?;
let users_str = resp_text.as_string().unwrap();
let users_value: Value = serde_json::from_str(&users_str).unwrap();
let users_vec =
users_value["data"]["allUsers"].as_array().unwrap().to_owned();
使用 yew 封装的 FetchService
yew 中的 fetch
,对 stdweb
和 web-sys
进行了封装,我们无需指定再分别指定使用stdweb
还是 web-sys
。如 yew 中的 fetch
源码片段。
//! Service to send HTTP-request to a server.
cfg_if::cfg_if! {
if #[cfg(feature = "std_web")] {
mod std_web;
pub use std_web::*;
} else if #[cfg(feature = "web_sys")] {
mod web_sys;
pub use self::web_sys::*;
}
}
注:yew 0.19 发布计划中,
stdweb
将予以移除。
构建请求
本文中,笔者使用的示例为构建一个 GraphQL 请求。构建 GraphQL 请求查询体
QueryBody<Variables>
,或者不使用其的注意点,请参阅上文《使用 web-sys -> 构建请求》
部分。
yew 中,在将请求发送到服务器之前,基于 http
库重建了 Request
结构体,其请求体须实现 Into<Text>
或者 Into<Binary>
。
Text
和 Binary
是下述 Result
类型的别名:
pub type Text = Result<String, Error>;
pub type Binary = Result<Vec<u8>, Error>;
GET 请求示例:
use yew::format::Nothing;
use yew_services::fetch::Request;
let get_request = Request::get("https://127.0.0.1/rest/v1/get/users")
.body(Nothing)
.expect("Could not build that request");
POST 请求示例:
use serde_json::json;
use yew::format::Json;
use yew_services::fetch::Request;
let post_request = Request::post("https://127.0.0.1/gql/v1/users")
.header("Content-Type", "application/json")
.body(Json(&json!({"isBanned": "false"})))
.expect("Could not build that request.");
具体我们本次实现的 GraphQL 请求,实际代码相较于《使用 web-sys
》部分,就很精简了。如下所示:
...
// 构建 graphql 查询体
let build_query =
AllProjects::build_query(all_projects::Variables {});
let query = Json(&build_query);
// 构建请求
let request = Request::post(&gql_uri())
.body(query)
.expect("Could not build request.");
...
发送请求
yew 中的 FetchService
,提供了到浏览器的 fetch
API 的绑定,请求可以通过 FetchService::fetch
或者 FetchService::fetch_with_options(附有请求选项,如 cookie)
方法来发送。
FetchService::fetch
具有 2 个参数:Request
对象和 Callback
。回调(Callback)
须实现 FormatDataType<Result<T, ::anyhow::Error>>
,而非 FormatDataType<T>
。
也就是说,具体代码是这样的:
self.link.callback(|response: Json<anyhow::Result<Json>>|)
而不能是:
self.link.callback(|response: Json<Json>|)
结合我们的示例业务,完整代码如下:
....
// 构造回调
let callback = self.link.callback(
|response: Response<Result<String, anyhow::Error>>| {
let resp_body = response.into_body();
let resp_str = resp_body.as_ref().unwrap();
...
},
);
// 传递请求和回调
let task = FetchService::fetch(request, callback)
.expect("failed to start request");
...
数据解析
最后,结合自己的业务逻辑,再通过一系列类型转换,如文本、数组等,使其成为我们可以渲染到页面的数据。
...
let projects_value: Value =
from_str(&resp_str).unwrap();
let projects_vec = projects_value["data"]
["allProjects"]
.as_array()
.unwrap()
.to_owned();
...
本文是基于前述文章基础之上的,所以直接阅读仅能是概念上的了解。如果你希望对其践行,建议阅读系列文章。
完整代码放置在 github,若感兴趣,请下载 zzy/tide-async-graphql-mongodb。
谢谢您的阅读!