use std::str::FromStr;
use url::{ParseError, Url};
#[derive(Clone, Debug)]
pub struct UrlBuilder {
root: Url,
collections: Url,
collections_with_slash: Url,
conformance: Url,
service_desc: Url,
search: Url,
}
impl UrlBuilder {
pub fn new(url: &str) -> Result<UrlBuilder, ParseError> {
let root: Url = if url.ends_with('/') {
url.parse()?
} else {
format!("{url}/").parse()?
};
Ok(UrlBuilder {
collections: root.join("collections")?,
collections_with_slash: root.join("collections/")?,
conformance: root.join("conformance")?,
service_desc: root.join("api")?,
search: root.join("search")?,
root,
})
}
pub fn root(&self) -> &Url {
&self.root
}
pub fn collections(&self) -> &Url {
&self.collections
}
pub fn collection(&self, id: &str) -> Result<Url, ParseError> {
self.collections_with_slash.join(id)
}
pub fn items(&self, id: &str) -> Result<Url, ParseError> {
self.collections_with_slash.join(&format!("{id}/items"))
}
pub fn item(&self, collection_id: &str, id: &str) -> Result<Url, ParseError> {
self.collections_with_slash
.join(&format!("{collection_id}/items/{id}"))
}
pub fn conformance(&self) -> &Url {
&self.conformance
}
pub fn service_desc(&self) -> &Url {
&self.service_desc
}
pub fn search(&self) -> &Url {
&self.search
}
}
impl FromStr for UrlBuilder {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
UrlBuilder::new(s)
}
}