Skip to main content

threads_rs/api/
location.rs

1use std::collections::HashMap;
2
3use crate::client::Client;
4use crate::constants;
5use crate::error;
6use crate::types::{Location, LocationId, LocationSearchResponse};
7
8impl Client {
9    /// Search for locations by query string, coordinates, or both.
10    ///
11    /// Per the API docs, you can search by `query` alone, `latitude` + `longitude`
12    /// alone, or all three together. At least one of `query` or coordinates must
13    /// be provided.
14    pub async fn search_locations(
15        &self,
16        query: Option<&str>,
17        latitude: Option<f64>,
18        longitude: Option<f64>,
19    ) -> crate::Result<LocationSearchResponse> {
20        let has_query = query.is_some_and(|q| !q.is_empty());
21        let has_coords = latitude.is_some() && longitude.is_some();
22
23        if !has_query && !has_coords {
24            return Err(error::new_validation_error(
25                0,
26                "Either a search query or latitude+longitude coordinates are required",
27                "",
28                "query",
29            ));
30        }
31
32        let token = self.access_token().await;
33        let mut params = HashMap::new();
34        params.insert("fields".into(), constants::LOCATION_FIELDS.into());
35
36        if let Some(q) = query {
37            if !q.is_empty() {
38                params.insert("q".into(), q.to_owned());
39            }
40        }
41
42        if let Some(lat) = latitude {
43            params.insert("latitude".into(), lat.to_string());
44        }
45        if let Some(lng) = longitude {
46            params.insert("longitude".into(), lng.to_string());
47        }
48
49        let resp = self
50            .http_client
51            .get("/location_search", params, &token)
52            .await?;
53        resp.json()
54    }
55
56    /// Get a location by ID.
57    pub async fn get_location(&self, location_id: &LocationId) -> crate::Result<Location> {
58        if !location_id.is_valid() {
59            return Err(error::new_validation_error(
60                0,
61                "Location ID is required",
62                "",
63                "location_id",
64            ));
65        }
66
67        let token = self.access_token().await;
68        let mut params = HashMap::new();
69        params.insert("fields".into(), constants::LOCATION_FIELDS.into());
70
71        let path = format!("/{}", location_id);
72        let resp = self.http_client.get(&path, params, &token).await?;
73        resp.json()
74    }
75}