nomi4m 0.1.0-rc.1

A rust client for nominatim.
Documentation
use async_trait::async_trait;
use serde::{Serialize, de::DeserializeOwned};

use crate::{
    Nominatim, Result,
    formats::json::{JsonPlaceFormat, JsonV2PlaceFormat},
    types::CountryCodeIso3166_1Alpha2,
};

mod parameters;

use parameters::SearchParameters;
pub use parameters::SearchQueryBuilder;

/// Formats of an [`Nominatim::search`](https://nominatim.org/release-docs/latest/api/Search/) query output.
pub trait SearchFormat {
    /// The actual output type, which is often a [`Vec`] of the format type.
    type Output: DeserializeOwned;

    /// The query parameter string to send to the server to get this format back.
    const PARAMETER: &str;
}

impl SearchFormat for JsonPlaceFormat {
    type Output = Vec<JsonPlaceFormat>;
    const PARAMETER: &str = "json";
}

impl SearchFormat for JsonV2PlaceFormat {
    type Output = Vec<JsonV2PlaceFormat>;
    const PARAMETER: &str = "jsonv2";
}

#[async_trait]
pub trait SearchQuery {
    async fn search<T: SearchFormat>(
        &self,
        client: &Nominatim,
        email: &str,
        params: &SearchParameters,
    ) -> Result<T::Output>;
}

/// A wrapper type for [freeform queries](https://nominatim.org/release-docs/latest/api/Search/#free-form-query).
///
/// Generally easier to just use [`String`] or [`&str`] directly.
#[derive(Debug, Clone)]
pub struct FreeformQuery(String);

#[async_trait]
impl SearchQuery for FreeformQuery {
    async fn search<T: SearchFormat>(
        &self,
        client: &Nominatim,
        email: &str,
        params: &SearchParameters,
    ) -> Result<T::Output> {
        Ok(client
            .client
            .get(client.search_url()?)
            .query(&[
                ("q", self.0.as_str()),
                ("format", T::PARAMETER),
                ("email", email),
            ])
            .query(&params)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }
}

impl From<String> for FreeformQuery {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for FreeformQuery {
    fn from(value: &str) -> Self {
        Self(value.into())
    }
}

#[async_trait]
impl SearchQuery for String {
    async fn search<T: SearchFormat>(
        &self,
        client: &Nominatim,
        email: &str,
        params: &SearchParameters,
    ) -> Result<T::Output> {
        Into::<FreeformQuery>::into(self.clone())
            .search::<T>(client, email, params)
            .await
    }
}

#[async_trait]
impl SearchQuery for &str {
    async fn search<T: SearchFormat>(
        &self,
        client: &Nominatim,
        email: &str,

        params: &SearchParameters,
    ) -> Result<T::Output> {
        Into::<FreeformQuery>::into(*self)
            .search::<T>(client, email, params)
            .await
    }
}

/// [Structured queries](https://nominatim.org/release-docs/latest/api/Search/#structured-query) for [`Nominatim::search`].
///
/// This follows the builder pattern, so see the relevant methods that correspond with the
/// different query parameters.
#[derive(Debug, Clone, Default, Serialize)]
pub struct StructuredQuery {
    #[serde(skip_serializing_if = "Option::is_none")]
    amenity: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    street: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    city: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    county: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    state: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    country: Option<CountryCodeIso3166_1Alpha2>,
    #[serde(skip_serializing_if = "Option::is_none")]
    postalcode: Option<String>,
}

impl StructuredQuery {
    /// Set the amenity (name and/or type of POI).
    pub fn amenity(mut self, amenity: impl ToString) -> Self {
        self.amenity = Some(amenity.to_string());
        self
    }

    /// Set the street (housenumber and streetname).
    pub fn street(mut self, street: impl ToString) -> Self {
        self.street = Some(street.to_string());
        self
    }

    /// Set the city.
    pub fn city(mut self, city: impl ToString) -> Self {
        self.city = Some(city.to_string());
        self
    }

    /// Set the county.
    pub fn county(mut self, county: impl ToString) -> Self {
        self.county = Some(county.to_string());
        self
    }

    /// Set the state.
    pub fn state(mut self, state: impl ToString) -> Self {
        self.state = Some(state.to_string());
        self
    }

    /// Set the country.
    pub fn country(mut self, country: CountryCodeIso3166_1Alpha2) -> Self {
        self.country = Some(country);
        self
    }

    /// Set the postal code.
    pub fn postalcode(mut self, postalcode: impl ToString) -> Self {
        self.postalcode = Some(postalcode.to_string());
        self
    }
}

#[async_trait]
impl SearchQuery for StructuredQuery {
    async fn search<T: SearchFormat>(
        &self,
        client: &Nominatim,
        email: &str,
        params: &SearchParameters,
    ) -> Result<T::Output> {
        Ok(client
            .client
            .get(client.search_url()?)
            .query(&self)
            .query(&[("format", T::PARAMETER), ("email", email)])
            .query(&params)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn structuredquery_serialization_empty() {
        let actual = serde_urlencoded::to_string(StructuredQuery::default()).unwrap();
        assert_eq!("", actual);
    }

    #[test]
    fn structuredquery_serialization_everything() {
        let actual = serde_urlencoded::to_string(
            StructuredQuery::default()
                .amenity("cafe")
                .street("broadway")
                .county("new york")
                .state("new york")
                .country("us".parse().unwrap())
                .postalcode(10017),
        )
        .unwrap();
        assert_eq!(
            "amenity=cafe&street=broadway&county=new+york&state=new+york&country=us&postalcode=10017",
            actual
        );
    }
}