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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//! Format URLs for fetch requests using templates and substitution values.
//!
//! ## Usage
//! ```
//! use format_url::FormatUrl;
//!
//! let url = FormatUrl::new("https://api.example.com/")
//!     .with_path_template("/user/:name")
//!     .with_substitutes(vec![("name", "alex")])
//!     .with_query_params(vec![("active", "true")])
//!     .format_url()
//!     .unwrap();
//!
//! assert_eq!(url, "https://api.example.com/user/alex?active=true");
//! ```
//!
//! ## Wishlist
//! * Support for lists and nested values. (serde_urlencoded -> serde_qs)
//! * No need to annotate generic T for FormatUrl

use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
use serde::Serialize;

type SubstitutePairs<'a> = Vec<(&'a str, &'a str)>;

fn strip_double_slash<'a>(base_url: &str, route_template: &'a str) -> &'a str {
    if base_url.ends_with("/") && route_template.starts_with("/") {
        &route_template[1..]
    } else {
        route_template
    }
}

fn format_path(route_template: &str, substitutes: &SubstitutePairs) -> String {
    substitutes
        .iter()
        .fold(route_template.to_owned(), |route, (key, value)| {
            route.replace(
                &format!(":{}", key),
                &utf8_percent_encode(&value, NON_ALPHANUMERIC).to_string(),
            )
        })
}

pub struct FormatUrl<'a, T: Serialize> {
    base: &'a str,
    path_template: Option<&'a str>,
    query_params: Option<T>,
    substitutes: Option<SubstitutePairs<'a>>,
}

impl<'a, T: Serialize> FormatUrl<'a, T> {
    pub fn new(base: &'a str) -> Self {
        Self {
            base,
            path_template: None,
            query_params: None,
            substitutes: None,
        }
    }

    pub fn with_path_template(mut self, path_template: &'a str) -> Self {
        self.path_template = Some(path_template);
        self
    }

    pub fn with_query_params(mut self, params: T) -> Self {
        self.query_params = Some(params);
        self
    }

    pub fn with_substitutes(mut self, substitutes: SubstitutePairs<'a>) -> Self {
        self.substitutes = Some(substitutes);
        self
    }

    pub fn format_url(self) -> Result<String, serde_urlencoded::ser::Error> {
        let formatted_path = match (self.path_template, &self.substitutes) {
            (Some(path_template), Some(substitutes)) => format_path(path_template, &substitutes),
            (Some(path_template), _) => path_template.to_string(),
            _ => String::from(""),
        };

        let formatted_querystring = &self.query_params.map_or_else(
            || Ok(String::new()),
            |query_params| {
                let query_string = serde_urlencoded::to_string(query_params)?;
                Ok(String::from("?") + (&query_string))
            },
        )?;

        let safe_formatted_route = strip_double_slash(self.base, &formatted_path);

        Ok(format!(
            "{}{}{}",
            self.base, safe_formatted_route, formatted_querystring
        ))
    }
}

#[cfg(test)]
mod tests {
    use crate::{FormatUrl, SubstitutePairs};

    #[test]
    fn accepts_empty_path() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com").format_url(),
            Ok("https://api.example.com".to_string())
        );
    }

    #[test]
    fn adds_path_to_base() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com/user",)
                .format_url()
                .unwrap(),
            "https://api.example.com/user"
        );
    }

    #[test]
    fn strips_double_slash() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com/user")
                .format_url()
                .unwrap(),
            "https://api.example.com/user"
        );
    }

    #[test]
    fn adds_path_substitutes() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com/",)
                .with_path_template("/user/:id",)
                .with_substitutes(vec![("id", "alextes")])
                .format_url()
                .unwrap(),
            "https://api.example.com/user/alextes"
        );
    }

    #[test]
    fn adds_querystring() {
        assert_eq!(
            FormatUrl::new("https://api.example.com/user",)
                .with_query_params(vec![("id", "alextes")],)
                .format_url()
                .unwrap(),
            "https://api.example.com/user?id=alextes"
        );
    }

    #[test]
    fn percent_encodes_substitutes() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com/",)
                .with_path_template("/user/:id",)
                .with_substitutes(vec![("id", "alex tes")])
                .format_url()
                .unwrap(),
            "https://api.example.com/user/alex%20tes"
        )
    }

    #[test]
    fn percent_encodes_query_params() {
        assert_eq!(
            FormatUrl::<SubstitutePairs>::new("https://api.example.com/user",)
                .with_query_params(vec![("id", "alex+tes")],)
                .format_url()
                .unwrap(),
            "https://api.example.com/user?id=alex%2Btes"
        )
    }

    #[test]
    fn test_v2_format_url() {
        assert_eq!(
            FormatUrl::new("https://api.example.com/")
                .with_path_template("/user/:name")
                .with_substitutes(vec![("name", "alex")])
                .with_query_params(vec![("active", "true")])
                .format_url()
                .unwrap(),
            "https://api.example.com/user/alex?active=true"
        )
    }
}