generated from ElnuDev/rust-project
34 lines
No EOL
924 B
Rust
34 lines
No EOL
924 B
Rust
use leptos::*;
|
|
use wasm_bindgen_futures::JsFuture;
|
|
use web_sys::{File, Window, Request};
|
|
|
|
use crate::error::{ReadFileError, FetchFileError};
|
|
|
|
pub fn window() -> Window {
|
|
web_sys::window().unwrap()
|
|
}
|
|
|
|
pub async fn read_file(
|
|
file: ReadSignal<Option<File>>,
|
|
) -> Result<String, ReadFileError> {
|
|
let file = match file() {
|
|
Some(file) => file,
|
|
None => return Err(ReadFileError::NoFile),
|
|
};
|
|
match JsFuture::from(file.text())
|
|
.await?
|
|
.as_string()
|
|
{
|
|
Some(contents) => Ok(contents),
|
|
None => Err(ReadFileError::ParseToString),
|
|
}
|
|
}
|
|
|
|
pub async fn fetch_file(url: &str) -> Result<String, FetchFileError> {
|
|
let request = Request::new_with_str(url)?;
|
|
let response = JsFuture::from(window().fetch_with_request(&request)).await?;
|
|
match response.as_string() {
|
|
Some(string) => Ok(string),
|
|
None => Err(FetchFileError::ReadToString),
|
|
}
|
|
} |