-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmod.rs
58 lines (45 loc) · 1.5 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
pub mod proto;
use anyhow::Result;
use gloo::utils::window;
use reqwest::{header::CONTENT_TYPE, Url};
use web_sys::FormData;
use self::proto::DirectoryIndex;
pub struct FileDownload {
pub bytes: Vec<u8>,
pub mime: String,
}
pub struct Api {
base_url: Url,
}
impl Api {
pub fn new() -> Self {
let base_url = Url::parse(&window().location().href().unwrap()).unwrap();
Self { base_url }
}
pub async fn peek(&self, path: &str) -> Result<DirectoryIndex> {
let path = path.strip_prefix("/").unwrap();
let url = self.base_url.join(&format!("/api/v1/{path}"))?;
let index = reqwest::get(url).await?.json::<DirectoryIndex>().await?;
Ok(index)
}
pub async fn upload(&self, form_data: FormData) -> Result<()> {
let url = self.base_url.join("api/v1")?;
gloo::net::http::Request::post(url.as_ref())
.body(form_data)?
.send()
.await?;
Ok(())
}
pub async fn download(&self, path: &String) -> Result<FileDownload> {
let path = path.strip_prefix("/").unwrap();
let url = self.base_url.join(&format!("/api/v1/{path}"))?;
let res = reqwest::get(url).await?;
let headers = res.headers();
let mime = headers
.get(CONTENT_TYPE)
.map(|hv| hv.to_str().unwrap().to_string())
.unwrap_or("application/octet-stream".to_string());
let bytes = res.bytes().await?.to_vec();
Ok(FileDownload { bytes, mime })
}
}