Rust 和 Wasm 的融合,使用 yew 构建 web 前端(4)- 获取 GraphQL 数据并解析

2021年6月8日 383点热度 0人点赞 0条评论
在 Rust 生态,使用 yew 开发 WebAssembly 应用方面,我们已经介绍了《起步及 crate 选择》《组件和路由》,以及《资源文件及重构》。今天,我们介绍如何在 yew 开发的 wasm 前端应用中,与后端进行数据交互。我们的后端提供了 GraphQL 服务,让我们获取 GraphQL 数据并解析吧!
需要新引入一些 crate:使用 graphql_client 获取 GraphQL 数据,然后通过 serde 进行解析。wasm 需要绑定 web API,以发起请求调用和接受响应数据,需要使用 web-sys,但其可以通过 yew 库路径引入,无需加入到依赖项。但是,web-sys 中和 JavaScript Promise 绑定和交互方面,需要 wasm-bindgen-futures。总体上,我们需要引入:
cargo add wasm-bindgen-futures graphql_client serde serde_json
现在,我们的 Cargo.toml 文件内容如下:
[package]name = "frontend-yew"version = "0.1.0"authors = ["我是谁?"]edition = "2018"
[dependencies]wasm-bindgen = "0.2.74"wasm-bindgen-futures = "0.4.24"
yew = "0.18.0"yew-router = "0.15.0"
graphql_client = "0.9.0"serde = { version = "1.0.126", features = ["derive"] }serde_json = "1.0.64"

编写 GraphQL 数据查询描述

首先,我们需要从 GraphQL 服务后端下载 schema.graphql,放置到 frontend-yew/graphql 文件夹中。schema 是我们要描述的 GraphQL 查询的类型系统,包括可用字段,以及返回对象等。
然后,在 frontend-yew/graphql 文件夹中创建一个新的文件 all_projects.graphql,描述我们要查询的项目数据。项目数据查询很简单,我们查询所有项目,不需要传递参数:
query AllProjects {  allProjects {    id    userId    subject    website  }}
最后,在 frontend-yew/graphql 文件夹中创建一个新的文件 all_users.graphql,描述我们要查询的用户数据。用户的查询,需要权限。也就是说,我们需要先进行用户认证,用户获取到自己在系统的令牌(token)后,才可以查看系统用户数据。每次查询及其它操作,用户都要将令牌(token)作为参数,传递给服务后端,以作验证。
query AllUsers($token: String!) {  allUsers(    token: $token  ) {    id    email    username  }}
用户需要签入系统,才能获取个人令牌(token)。此部分我们不做详述,请参阅文章《基于 tide + async-graphql + mongodb 构建异步 Rust GraphQL 服务》、《基于 actix-web + async-graphql + rbatis + postgresql / mysql 构建异步 Rust GraphQL 服务》,以及项目 zzy/tide-async-graphql-mongodb 进行了解。

请求(request)的构建

使用 graphql_client 构建查询体(QueryBody)

在此,我们需要使用到上一节定义的 GraphQL 查询描述,通过 GraphQLQuery 派生属性注解,可以实现与查询描述文件(如 all_users.graphql)中查询同名的结构体。当然,Rust 文件中,结构体仍然需要我们定义,注意与查询描述文件中的查询同名。如,与 all_users.graphql 查询描述文件对应的代码为:
#[derive(GraphQLQuery)]#[graphql(    schema_path = "./graphql/schema.graphql",    query_path = "./graphql/all_users.graphql",    response_derives = "Debug")]struct AllUsers;type ObjectId = String;
type ObjectId = String; 表示我们直接从 MongoDB 的 ObjectId 中提取其 id 字符串。
接下来,我们构建 graphql_client 查询体(QueryBody),我们要将其转换为 Value 类型。项目列表查询没有参数,构造简单。我们以用户列表查询为例,传递我们使用 PBKDF2 对密码进行加密(salt)和散列(hash)运算后的令牌(token)。
本文实例中,为了演示,我们将令牌(token)获取后,作为字符串传送,实际应用代码中,当然是作为 cookie/session 参数来获取的,不会进行明文编码。
    let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJlbWFpbCI6ImFzZmZhQGRzYWZhLmNvbSIsInVzZXJuYW1lIjoi5a-G56CBMTExIiwiZXhwIjoxMDAwMDAwMDAwMH0.NyEN13J5trkn9OlRqWv2xMHshysR9QPWclo_-q1cbF4y_9rbkpSI6ern-GgKIh_ED0Czk98M1fJ6tzLczbdptg";    let build_query = AllUsers::build_query(all_users::Variables {        token: token.to_string(),    });    let query = serde_json::json!(build_query);

构造 web-sys 请求

构建 web-sys 请求时:
  • 我们需要设定请求的方法(method),GraphQL 请求须为 POST
  • 我们需要将 graphql_client 查询体(QueryBody)转换为字符串,压入到 web-sys 请求体中。
  • 可选地,我们需要声明查询请求是否为跨域资源共享(Cross-Origin Resource Sharing)。web-sys 请求中,默认为跨域资源共享。
    let mut req_opts = RequestInit::new();    req_opts.method("POST");    req_opts.body(Some(&JsValue::from_str(&query.to_string())));    req_opts.mode(RequestMode::Cors); // 可以不写,默认为 Cors
let gql_uri = "http://127.0.0.1:8000/graphql"; let request = Request::new_with_str_and_init(gql_uri, &req_opts)?;
注 1:如果你遇到同源策略禁止读取的错误提示,请检查服务后端是否设定了 Access-Control-Allow-Origin 指令,指令可以用通配符 * 或者指定数据源链接地址(可为列表)。
注 2let gql_uri = "http://127.0.0.1:8000/graphql"; 一行,实际项目中,通过配置环境变量来读取,是较好的体验。

响应(response)数据的接收和解析

响应(response)数据的接收

响应(response)数据的接受部分代码,来自 sansx(yew 中文文档翻译者) 的 yew 示例项目 sansx/yew-graphql-demo。
提交请求方面,web-sys 提供了四种方式:
  • Window::fetch_with_str
  • Window::fetch_with_request
  • Window::fetch_with_str_and_init
  • Window::fetch_with_request_and_init
我们使用 Window::fetch_with_request 提交请求,返回的数据为 JsValue,需要通过 dyn_into() 方法转换为响应(Response)类型。
   let window = yew::utils::window();    let resp_value =        JsFuture::from(window.fetch_with_request(&request)).await?;    let resp: Response = resp_value.dyn_into().unwrap();    let resp_text = JsFuture::from(resp.text()?).await?;

响应(response)数据的解析

我们接收到的数据是 JsValue 类型。首先,需要将其转换为 Value 类型,再提取我们需要的目标数据。本文示例中,我们需要的目标数据都是列表,所以转换为动态数组(Vector)。
    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();
Ok(users_vec)
数据的渲染

我们实现了数据获取、转换,以及部分解析。但是,组件的状态和数据请求的关联——如前几篇文章所述——是通过 yew 中的 Message 关联的。如,组件和消息的定义:
pub struct Users {    list: Vec<Value>,    link: ComponentLink<Self>,}
pub enum Msg { UpdateList(Vec<Value>),}
组件定义方面,我们不再赘述。我们集中于数据展示渲染方面:yew 的 html! 宏中,是不能使用 for <val> in Vec<val> 这样的循环控制语句的,其也不能和 html! 宏嵌套使用。但 html! 宏中提供了 for 关键字,用于对包含项(item)类型为 VNode 的迭代体(即实现了 Iterator)进行渲染。如用户列表的渲染代码:
   fn view(&self) -> Html {        let users = self.list.iter().map(|user| {            html! {                <div>                    <li>                        <strong>                            { &user["username"].as_str().unwrap() }                            { " - length: " }                            { &user["username"].as_str().unwrap().len() }                        </strong>                    </li>                    <ul>                        <li>{ &user["id"].as_str().unwrap() }</li>                        <li>{ &user["email"].as_str().unwrap() }</li>                    </ul>                </div>            }        });
html! { <> <h1>{ "all users" }</h1> <ul> { for users } </ul> </> } }}
对于项目列表的数据展示,是类似的,不过我们需要注意的一点为:yew 中的数据输出,有字面量和 IntoPropValue 两种。前者比较灵活:String 和 &str 均可;而后者须为实现 IntoPropValue<std::option::Option<Cow<'static, str>>> 特质(trait)的类型,如 String。比如:项目列表中,对于链接的 href 属性,必须是实现了 IntoPropValue<std::option::Option<Cow<'static, str>>> 特质(trait)的 String,而直接输出的字面量则不同。
    <a href={ project["website"].as_str().unwrap().to_owned() }>        { &project["website"].as_str().unwrap() }    </a>

完整代码

推荐你从项目 zzy/tide-async-graphql-mongodb 下载完整代码,更欢迎你做出任何贡献。

pages/users.rs

use graphql_client::GraphQLQuery;use serde_json::Value;use std::fmt::Debug;use wasm_bindgen::{prelude::*, JsCast};use wasm_bindgen_futures::{spawn_local, JsFuture};use yew::web_sys::{Request, RequestInit, RequestMode, Response};use yew::{html, Component, ComponentLink, Html, ShouldRender};
#[derive(Debug, Clone, PartialEq)]pub struct FetchError { err: JsValue,}
impl From<JsValue> for FetchError { fn from(value: JsValue) -> Self { Self { err: value } }}
#[derive(GraphQLQuery)]#[graphql( schema_path = "./graphql/schema.graphql", query_path = "./graphql/all_users.graphql", response_derives = "Debug")]struct AllUsers;type ObjectId = String;
async fn fetch_users() -> Result<Vec<Value>, FetchError> { let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJlbWFpbCI6ImFzZmZhQGRzYWZhLmNvbSIsInVzZXJuYW1lIjoi5a-G56CBMTExIiwiZXhwIjoxMDAwMDAwMDAwMH0.NyEN13J5trkn9OlRqWv2xMHshysR9QPWclo_-q1cbF4y_9rbkpSI6ern-GgKIh_ED0Czk98M1fJ6tzLczbdptg"; 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()))); req_opts.mode(RequestMode::Cors); // 可以不写,默认为 Cors
let gql_uri = "http://127.0.0.1:8000/graphql"; let request = Request::new_with_str_and_init(gql_uri, &req_opts)?;
let window = yew::utils::window(); let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; let resp: Response = resp_value.dyn_into().unwrap(); 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();
Ok(users_vec)}
pub struct Users { list: Vec<Value>, link: ComponentLink<Self>,}
pub enum Msg { UpdateList(Vec<Value>),}
impl Component for Users { type Message = Msg; type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { list: Vec::new(), link } }
fn rendered(&mut self, first_render: bool) { let link = self.link.clone(); if first_render { spawn_local(async move { let res = fetch_users().await; link.send_message(Msg::UpdateList(res.unwrap())) }); } }
fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::UpdateList(res) => { self.list = res; true } } }
fn change(&mut self, _props: Self::Properties) -> ShouldRender { false }
fn view(&self) -> Html { let users = self.list.iter().map(|user| { html! { <div> <li> <strong> { &user["username"].as_str().unwrap() } { " - length: " } { &user["username"].as_str().unwrap().len() } </strong> </li> <ul> <li>{ &user["id"].as_str().unwrap() }</li> <li>{ &user["email"].as_str().unwrap() }</li> </ul> </div> } });
html! { <> <h1>{ "all users" }</h1> <ul> { for users } </ul> </> } }}

pages/projects.rs

use graphql_client::GraphQLQuery;use serde_json::Value;use std::fmt::Debug;use wasm_bindgen::{prelude::*, JsCast};use wasm_bindgen_futures::{spawn_local, JsFuture};use yew::web_sys::{Request, RequestInit, RequestMode, Response};use yew::{html, Component, ComponentLink, Html, ShouldRender};
#[derive(Debug, Clone, PartialEq)]pub struct FetchError { err: JsValue,}
impl From<JsValue> for FetchError { fn from(value: JsValue) -> Self { Self { err: value } }}
#[derive(GraphQLQuery)]#[graphql( schema_path = "./graphql/schema.graphql", query_path = "./graphql/all_projects.graphql", response_derives = "Debug")]struct AllProjects;type ObjectId = String;
async fn fetch_projects() -> Result<Vec<Value>, FetchError> { let build_query = AllProjects::build_query(all_projects::Variables {}); let query = serde_json::json!(build_query);
let mut opts = RequestInit::new(); opts.method("POST"); opts.body(Some(&JsValue::from_str(&query.to_string()))); opts.mode(RequestMode::Cors); // 可以不写,默认为 Cors
let gql_uri = "http://127.0.0.1:8000/graphql"; let request = Request::new_with_str_and_init(gql_uri, &opts)?;
let window = yew::utils::window(); let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; let resp: Response = resp_value.dyn_into().unwrap(); let resp_text = JsFuture::from(resp.text()?).await?;
let projects_str = resp_text.as_string().unwrap(); let projects_value: Value = serde_json::from_str(&projects_str).unwrap(); let projects_vec = projects_value["data"]["allProjects"].as_array().unwrap().to_owned();
Ok(projects_vec)}
pub struct Projects { list: Vec<Value>, link: ComponentLink<Self>,}
pub enum Msg { UpdateList(Vec<Value>),}
impl Component for Projects { type Message = Msg; type Properties = ();
fn create(_props: Self::Properties, link: ComponentLink<Self>) -> Self { Self { list: Vec::new(), link } }
fn rendered(&mut self, first_render: bool) { let link = self.link.clone(); if first_render { spawn_local(async move { let res = fetch_projects().await; link.send_message(Msg::UpdateList(res.unwrap())) }); } }
fn update(&mut self, msg: Self::Message) -> ShouldRender { match msg { Msg::UpdateList(res) => { self.list = res; true } } }
fn change(&mut self, _props: Self::Properties) -> ShouldRender { false }
fn view(&self) -> Html { let projects = self.list.iter().map(|project| { html! { <div> <li> <strong>{ &project["subject"].as_str().unwrap() }</strong> </li> <ul> <li>{ &project["userId"].as_str().unwrap() }</li> <li>{ &project["id"].as_str().unwrap() }</li> <li> <a href={ project["website"].as_str().unwrap().to_owned() }> { &project["website"].as_str().unwrap() } </a> </li> </ul> </div> } });
html! { <> <h1>{ "all projects" }</h1> <ul> { for projects } </ul> </> } }}

运行和测试

执行 trunk serve 命令,浏览器会自动打开一个页面,或者手动在浏览器中访问 http://127.0.0.1:3001。如果你未按照上篇 trunk.toml 所介绍的配置,请访问你自定义的端口(默认为 8080)。
此次 WebAssembly 实践成果,如下图片所示,你可以和第二篇文章《组件和路由》中设定实现目标做以对比。
图片

结语

yew 开发 WebAssembly 前端的系列文章,本文即告以第一阶段。
如果你下载源码,也可以使用浏览器的性能基准测试功能,简单对模板引擎开发的 web 前端,和 yew 开发的 web 前端进行性能的粗略比较。
总体体验而言,笔者个人认为,yew 开发熟练以后,效率是较高的。同时,也可更加专注于业务。
后续的文章中,我们将进行更加深入的应用。
谢谢您的阅读,欢迎交流。如果您发现错别字,也请向我发信息:公众号内联系,或者加我微信 yupen-com 均可。
建议您通过阅读原文进行更详细的了解:获得资料链接(本文含大量页面链接)、完整代码。另外原文可以随意修改,错别字也少一些  ;-)。

41640Rust 和 Wasm 的融合,使用 yew 构建 web 前端(4)- 获取 GraphQL 数据并解析

这个人很懒,什么都没留下

文章评论