Skip to main content

impulse_ui_kit/
router.rs

1//! Methods to work with routes on SPA.
2
3use impulse_utils::prelude::*;
4
5/// Get server's address and port
6pub fn get_host() -> CResult<String> {
7  let server_host = web_sys::window()
8    .ok_or(ClientError::from_str("Can't get browser's window parameters."))?
9    .document()
10    .ok_or(ClientError::from_str("Can't get window's document."))?
11    .location()
12    .ok_or(ClientError::from_str("Can't get document's location."))?
13    .host()
14    .map_err(|e| ClientError::from_str(format!("Can't get host: {e:?}")))?
15    .to_string();
16  Ok(server_host)
17}
18
19/// Get server protocol (HTTP/HTTPS: "http:"/"https:")
20pub fn get_protocol() -> CResult<String> {
21  let server_proto = web_sys::window()
22    .ok_or(ClientError::from_str("Can't get browser's window parameters."))?
23    .document()
24    .ok_or(ClientError::from_str("Can't get window's document."))?
25    .location()
26    .ok_or(ClientError::from_str("Can't get document's location."))?
27    .protocol()
28    .map_err(|e| ClientError::from_str(format!("Can't get protocol: {e:?}")))?
29    .to_string();
30  Ok(server_proto)
31}
32
33/// Get path
34pub fn get_path() -> CResult<String> {
35  let path = web_sys::window()
36    .ok_or(ClientError::from_str("Can't get browser's window parameters."))?
37    .document()
38    .ok_or(ClientError::from_str("Can't get window's document."))?
39    .location()
40    .ok_or(ClientError::from_str("Can't get document's location."))?
41    .pathname()
42    .map_err(|e| ClientError::from_str(format!("Can't get pathname: {e:?}")))?
43    .to_string();
44  Ok(path)
45}
46
47/// Redirect to any URL
48pub fn redirect(url: impl AsRef<str>) -> CResult<()> {
49  web_sys::window()
50    .ok_or(ClientError::from_str("Can't get browser's window parameters."))?
51    .document()
52    .ok_or(ClientError::from_str("Can't get window's document."))?
53    .location()
54    .ok_or(ClientError::from_str("Can't get document's location."))?
55    .set_href(url.as_ref())
56    .map_err(|e| ClientError::from_str(format!("Can't redirect: {e:?}")))
57}
58
59/// Get endpoint to your backend server
60///
61/// Example:
62///
63/// ```rust,ignore
64/// use impulse_ui_kit::router::endpoint;
65///
66/// fn main() {
67///   // Let assume that your backend is located at `127.0.0.1:8080` with HTTP schema
68///   assert_eq!(endpoint("/some/api/route").as_str(), "http://127.0.0.1:8080/some/api/route");
69/// }
70/// ```
71pub fn endpoint(api_uri: impl AsRef<str>) -> String {
72  format!(
73    "{}//{}{}",
74    get_protocol().unwrap(),
75    get_host().unwrap(),
76    api_uri.as_ref()
77  )
78}