Skip to content

Commit

Permalink
Create websocket connection
Browse files Browse the repository at this point in the history
  • Loading branch information
samoylovfp committed May 5, 2022
1 parent 59c52d5 commit 893e2ce
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 24 deletions.
81 changes: 58 additions & 23 deletions front-end/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,85 @@
mod server_api;

use server_api::LoginResponse;
use yew::{function_component, html, use_state, Html, Callback, Component};
use yew::{
function_component, html, html::Scope, use_state, Callback, Component, Html, Properties,
};

use log::*;
use serde_json::json;
use web_sys::FocusEvent;
use yew_hooks::use_async;
use yew_hooks::{use_async, use_web_socket};

enum Status {
NotLoggedIn,
LoggedIn { jwt: String },
enum AppMsg {
SuccessfulLogin { jwt: String },
}

struct App;
struct App {
jwt: Option<String>,
}

impl Component for App {
type Message = ();
type Message = AppMsg;

type Properties = ();

fn create(ctx: &yew::Context<Self>) -> Self {
App
fn create(_ctx: &yew::Context<Self>) -> Self {
App { jwt: None }
}

fn update(&mut self, _ctx: &yew::Context<Self>, msg: Self::Message) -> bool {
match msg {
AppMsg::SuccessfulLogin { jwt } => self.jwt = Some(jwt),
}
true
}

fn view(&self, ctx: &yew::Context<Self>) -> Html {
let onsubmit = Callback::from(|focus_event: FocusEvent| {
let link = ctx.link().clone();
let onsubmit = Callback::once(|focus_event: FocusEvent| {
focus_event.prevent_default();

wasm_bindgen_futures::spawn_local(login("daniil", "hello"));


wasm_bindgen_futures::spawn_local(login("daniil", "hello", link));
});
html! {
<form onsubmit={onsubmit}>
<label for="username">{ "Username:" }</label><br />
<input type="text" id="username" name="username" /><br />
<label for="pwd">{ "Password:" }</label><br />
<input type="password" id="pwd" name="pwd" /><br />
<input type="submit"/>
</form>
if let Some(jwt) = &self.jwt {
html! {
<Connection jwt={jwt.clone()} />
}
} else {
html! {
<form onsubmit={onsubmit}>
<label for="username">{ "Username:" }</label><br />
<input type="text" id="username" name="username" /><br />
<label for="pwd">{ "Password:" }</label><br />
<input type="password" id="pwd" name="pwd" /><br />
<input type="submit"/>
</form>
}
}
}
}

#[derive(Properties, PartialEq)]
struct ConnectionProps {
jwt: String,
}

#[function_component(Connection)]
fn connection(props: &ConnectionProps) -> Html {
let ws = use_web_socket("ws://localhost:8080/web-socket".to_string());
ws.send(
json!({
"_type": "jwt",
"jwt": &format!("Bearer {}", props.jwt)
})
.to_string(),
);
html!(
<h2>{"connection"}</h2>
)
}

async fn login(username: &str, password: &str) {
async fn login(username: &str, password: &str, link: Scope<App>) {
let response: LoginResponse = reqwest::Client::new()
.post("http://localhost:8080/login")
.json(&json!({
Expand All @@ -58,7 +93,7 @@ async fn login(username: &str, password: &str) {
.await
.unwrap();

info!("{response:?}");
link.send_message(AppMsg::SuccessfulLogin { jwt: response.jwt });
}
fn main() {
std::panic::set_hook(Box::new(console_error_panic_hook::hook));
Expand Down
2 changes: 1 addition & 1 deletion front-end/src/server_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ pub enum Message {

#[derive(Deserialize, Clone, Debug)]
pub struct LoginResponse {
jwt: String,
pub jwt: String,
}

0 comments on commit 893e2ce

Please sign in to comment.