gloo_net/http/
query.rs

1use gloo_utils::iter::UncheckedIter;
2use js_sys::{Array, Map};
3use std::fmt;
4use wasm_bindgen::{JsCast, UnwrapThrowExt};
5
6/// A sequence of URL query parameters, wrapping [`web_sys::UrlSearchParams`].
7pub struct QueryParams {
8    raw: web_sys::UrlSearchParams,
9}
10
11impl Default for QueryParams {
12    fn default() -> Self {
13        Self::new()
14    }
15}
16
17#[allow(dead_code)]
18impl QueryParams {
19    /// Create a new empty query parameters object.
20    pub fn new() -> Self {
21        // pretty sure this will never throw.
22        Self {
23            raw: web_sys::UrlSearchParams::new().unwrap_throw(),
24        }
25    }
26
27    /// Create [`QueryParams`] from [`web_sys::UrlSearchParams`] object.
28    pub fn from_raw(raw: web_sys::UrlSearchParams) -> Self {
29        Self { raw }
30    }
31
32    /// Append a parameter to the query string.
33    pub fn append(&self, name: &str, value: &str) {
34        self.raw.append(name, value)
35    }
36
37    /// Get the value of a parameter. If the parameter has multiple occurrences, the first value is
38    /// returned.
39    pub fn get(&self, name: &str) -> Option<String> {
40        self.raw.get(name)
41    }
42
43    /// Get all associated values of a parameter.
44    pub fn get_all(&self, name: &str) -> Vec<String> {
45        self.raw
46            .get_all(name)
47            .iter()
48            .map(|jsval| jsval.as_string().unwrap_throw())
49            .collect()
50    }
51
52    /// Remove all occurrences of a parameter from the query string.
53    pub fn delete(&self, name: &str) {
54        self.raw.delete(name)
55    }
56
57    /// Iterate over (name, value) pairs of the query parameters.
58    pub fn iter(&self) -> impl Iterator<Item = (String, String)> {
59        // Here we cheat and cast to a map even though `self` isn't, because the method names match
60        // and everything works. Is there a better way? Should there be a `MapLike` or
61        // `MapIterator` type in `js_sys`?
62        let fake_map: &Map = self.raw.unchecked_ref();
63        UncheckedIter::from(fake_map.entries()).map(|entry| {
64            let entry: Array = entry.unchecked_into();
65            let key = entry.get(0);
66            let value = entry.get(1);
67            (
68                key.as_string().unwrap_throw(),
69                value.as_string().unwrap_throw(),
70            )
71        })
72    }
73}
74
75/// The formatted query parameters ready to be used in a URL query string.
76///
77/// # Examples
78///
79/// The resulting string does not contain a leading `?` and is properly encoded:
80///
81/// ```
82/// # fn no_run() {
83/// use gloo_net::http::QueryParams;
84///
85/// let params = QueryParams::new();
86/// params.append("a", "1");
87/// params.append("b", "2");
88/// assert_eq!(params.to_string(), "a=1&b=2".to_string());
89///
90/// params.append("key", "ab&c");
91/// assert_eq!(params.to_string(), "a=1&b=2&key=ab%26c");
92/// # }
93/// ```
94impl fmt::Display for QueryParams {
95    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96        write!(f, "{}", self.raw.to_string())
97    }
98}
99
100impl fmt::Debug for QueryParams {
101    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
102        f.debug_list().entries(self.iter()).finish()
103    }
104}