Thanos did a thing

This commit is contained in:
LinlyBoi
2022-12-25 10:09:06 +02:00
parent f456749a66
commit f1aeeed085
3 changed files with 197 additions and 28 deletions

View File

@@ -1,3 +1,4 @@
use gloo::{console::log, utils::format::JsValueSerdeExt};
use std::{ use std::{
error::Error, error::Error,
fmt::{self, Debug, Display, Formatter}, fmt::{self, Debug, Display, Formatter},
@@ -47,61 +48,65 @@ impl UseAble for CommonAdmin {
} }
//Wwasm bingdengen code //Wwasm bingdengen code
const DRIVER_URL: &str = "http://libkyy.cf:48590/api/driver/1234"; const DRIVER_URL: &str = "http://db.sewelam.tech/api/driver/1234";
const FUNNY_TXT_URL: &str = "https://whatthecommit.com/index.txt";
const INCORRECT_URL: &str = "http://libkyy.cf"; const INCORRECT_URL: &str = "http://libkyy.cf";
//Generic Msg for our states
enum Msg { enum Msg<T> {
SetDriverFetchState(FetchState<String>), SetDataFetchState(FetchState<T>),
GetDriver, GetData,
GetError, GetError,
} }
struct Driver { struct RandomCommit {
driver: FetchState<String>, commit: FetchState<String>,
} }
impl Component for Driver { //This trait is for all yew components
type Message = Msg; impl Component for RandomCommit {
type Message = Msg<String>;
type Properties = (); type Properties = ();
fn create(_ctx: &Context<Self>) -> Self { fn create(_ctx: &Context<Self>) -> Self {
Self { Self {
driver: FetchState::NotFetching, commit: FetchState::NotFetching, //Default state is not fetching anything
} }
} }
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool { fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg { match msg {
Msg::SetDriverFetchState(fetch_state) => { Msg::SetDataFetchState(fetch_state) => {
self.driver = fetch_state; self.commit = fetch_state;
true true
} }
Msg::GetDriver => { Msg::GetData => {
ctx.link().send_future(async { ctx.link().send_future(async {
match fetch_driver(DRIVER_URL).await { match fetch_commit(FUNNY_TXT_URL).await {
Ok(driver) => Msg::SetDriverFetchState(FetchState::Success(driver)), Ok(commit) => Msg::SetDataFetchState(FetchState::Success(commit)),
Err(err) => Msg::SetDriverFetchState(FetchState::Failed(err)), Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
} }
}); });
ctx.link() ctx.link()
.send_message(Msg::SetDriverFetchState(FetchState::Fetching)); .send_message(Msg::SetDataFetchState(FetchState::Fetching));
false false
} }
Msg::GetError => { Msg::GetError => {
ctx.link().send_future(async { ctx.link().send_future(async {
match fetch_driver(INCORRECT_URL).await { match fetch_commit(INCORRECT_URL).await {
Ok(driver) => Msg::SetDriverFetchState(FetchState::Success(driver)), Ok(commit) => Msg::SetDataFetchState(FetchState::Success(commit)),
Err(err) => Msg::SetDriverFetchState(FetchState::Failed(err)), Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
} }
}); });
ctx.link() ctx.link()
.send_message(Msg::SetDriverFetchState(FetchState::Fetching)); .send_message(Msg::SetDataFetchState(FetchState::Fetching));
false false
} }
} }
} }
fn view(&self, ctx: &Context<Self>) -> Html { fn view(&self, ctx: &Context<Self>) -> Html {
match &self.driver { match &self.commit {
FetchState::NotFetching => html! { FetchState::NotFetching => html! {
<> <>
<button onclick={ctx.link().callback(|_| Msg::GetDriver)}> <button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get Driver" } { "Get commit msg" }
</button> </button>
<button onclick={ctx.link().callback(|_| Msg::GetError)}> <button onclick={ctx.link().callback(|_| Msg::GetError)}>
{ "Get using incorrect URL" } { "Get using incorrect URL" }
@@ -114,6 +119,72 @@ impl Component for Driver {
} }
} }
} }
//Generate Struct and implement component for driver using CommonDriver
struct Driver {
driver: FetchState<CommonDriver>,
}
impl Component for Driver {
type Message = Msg<CommonDriver>;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
driver: FetchState::NotFetching, //Default state is not fetching anything
}
}
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::SetDataFetchState(fetch_state) => {
self.driver = fetch_state;
true
}
Msg::GetData => {
ctx.link().send_future(async {
match fetch_driver(DRIVER_URL).await {
Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
Msg::GetError => {
ctx.link().send_future(async {
match fetch_driver(INCORRECT_URL).await {
Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
}
});
ctx.link()
.send_message(Msg::SetDataFetchState(FetchState::Fetching));
false
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
//render the component into HTML
match &self.driver {
FetchState::NotFetching => html! {
<>
<button onclick={ctx.link().callback(|_| Msg::GetData)}>
{ "Get driver info" }
</button>
<button onclick={ctx.link().callback(|_| Msg::GetError)}>
{ "Get using incorrect URL" }
</button>
</>
},
FetchState::Fetching => html! { "Fetching" },
FetchState::Success(data) => match data.clone().use_it() {
Ok(html) => html,
Err(err) => html! { err },
},
FetchState::Failed(err) => html! { err },
}
}
}
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct FetchError { pub struct FetchError {
@@ -125,6 +196,7 @@ impl Display for FetchError {
Debug::fmt(&self.err, f) Debug::fmt(&self.err, f)
} }
} }
impl Error for FetchError {} impl Error for FetchError {}
impl From<JsValue> for FetchError { impl From<JsValue> for FetchError {
@@ -132,6 +204,7 @@ impl From<JsValue> for FetchError {
Self { err: value } Self { err: value }
} }
} }
//Enum for Fetchstates that takes a generic type --> String/Driver etc.
pub enum FetchState<T> { pub enum FetchState<T> {
NotFetching, NotFetching,
Fetching, Fetching,
@@ -139,22 +212,54 @@ pub enum FetchState<T> {
Failed(FetchError), Failed(FetchError),
} }
//my code here poopy //Working example function
async fn fetch_driver(url: &'static str) -> Result<String, FetchError> { async fn fetch_commit(url: &'static str) -> Result<String, FetchError> {
//initialise request
let mut opts = RequestInit::new(); let mut opts = RequestInit::new();
opts.method("GET"); opts.method("GET");
opts.mode(RequestMode::Cors); opts.mode(RequestMode::Cors); //Cors is required for fetch to work
let request = Request::new_with_str_and_init(url, &opts)?; let request = Request::new_with_str_and_init(url, &opts)?;
let window = gloo::utils::window(); let window = gloo::utils::window();
//get response value
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
let resp: Response = resp_value.dyn_into().unwrap(); let resp: Response = resp_value.dyn_into().unwrap();
//parse response value as text
let text = JsFuture::from(resp.text()?).await?; let text = JsFuture::from(resp.text()?).await?;
Ok(text.as_string().unwrap()) Ok(text.as_string().unwrap())
} }
//render obama
async fn fetch_driver(url: &'static str) -> Result<CommonDriver, FetchError> {
let mut opts = RequestInit::new();
opts.method("GET");
//Available request modes: Cors, NoCors, SameOrigin
opts.mode(RequestMode::NoCors); //NoCors because cors simply doesn't work here
let request = Request::new_with_str_and_init(url, &opts)?;
//api header for json
request.headers().set("Accept", "application/json")?;
let window = web_sys::window().unwrap();
let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?;
assert!(resp_value.is_instance_of::<Response>());
let resp: Response = resp_value.dyn_into().unwrap();
//parsing Json response
let fetched_json = JsFuture::from(resp.json()?).await?;
log!(fetched_json.clone());
let fetched_json: JsValue = fetched_json.into();
//parsing into CommonDriver struct
let fetched_json: CommonDriver = fetched_json.into_serde().unwrap();
Ok(fetched_json)
}
//renders components above
pub fn render_commit() {
yew::Renderer::<RandomCommit>::new().render();
}
pub fn render_driver() { pub fn render_driver() {
yew::Renderer::<Driver>::new().render(); yew::Renderer::<Driver>::new().render();
} }

View File

@@ -65,5 +65,7 @@ struct Stdnt {
// } // }
fn main() { fn main() {
yew::Renderer::<App>::new().render();
fetching::render_commit();
fetching::render_driver(); fetching::render_driver();
} }

View File

@@ -0,0 +1,62 @@
// impl Component for Driver {
// type Message = Msg<CommonDriver>;
// type Properties = ();
// fn create(_ctx: &Context<Self>) -> Self {
// Self {
// driver: FetchState::NotFetching, //Default state is not fetching anything
// }
// }
//
// fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
// match msg {
// Msg::SetDataFetchState(fetch_state) => {
// self.driver = fetch_state;
// true
// }
// Msg::GetData => {
// ctx.link().send_future(async {
// match fetch_driver(DRIVER_URL).await {
// Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
// Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
// }
// });
// ctx.link()
// .send_message(Msg::SetDataFetchState(FetchState::Fetching));
// false
// }
// Msg::GetError => {
// ctx.link().send_future(async {
// match fetch_driver(INCORRECT_URL).await {
// Ok(driver) => Msg::SetDataFetchState(FetchState::Success(driver)),
// Err(err) => Msg::SetDataFetchState(FetchState::Failed(err)),
// }
// });
// ctx.link()
// .send_message(Msg::SetDataFetchState(FetchState::Fetching));
// false
// }
// }
// }
//
// fn view(&self, ctx: &Context<Self>) -> Html {
// //render the component into HTML
// match &self.driver {
// FetchState::NotFetching => html! {
// <>
// <button onclick={ctx.link().callback(|_| Msg::GetData)}>
// { "Get driver info" }
// </button>
// <button onclick={ctx.link().callback(|_| Msg::GetError)}>
// { "Get using incorrect URL" }
// </button>
// </>
// },
// FetchState::Fetching => html! { "Fetching" },
// FetchState::Success(data) => match data.clone().use_it() {
// Ok(html) => html,
// Err(err) => html! { err },
// },
// FetchState::Failed(err) => html! { err },
// }
// }
// }