Ardente

Untitled

Jun 11th, 2022
1,720
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.50 KB | None | 0 0
  1. use crate::TypeMapKey;
  2. use reqwest::Url;
  3. use serde::{Deserialize, Serialize};
  4. use serenity::prelude::*;
  5. use std::collections::HashMap;
  6. use std::sync::Arc;
  7.  
  8. #[derive(Debug, Clone, Serialize, Deserialize)]
  9. pub struct FuzzyResponse {
  10.     pub predictions: Vec<FuzzyLocation>,
  11. }
  12.  
  13. #[derive(Debug, Clone, Serialize, Deserialize)]
  14. pub struct FuzzyLocation {
  15.     pub description: String,
  16. }
  17.  
  18. pub struct CachedInputs;
  19.  
  20. impl TypeMapKey for CachedInputs {
  21.     type Value = Arc<Mutex<HashMap<String, FuzzyResponse>>>;
  22. }
  23.  
  24. pub async fn fuzzy_search(ctx: &Context, input: &str) -> anyhow::Result<FuzzyResponse> {
  25.     let cached_inputs = {
  26.         let data = ctx.data.read().await;
  27.  
  28.         data.get::<CachedInputs>()
  29.             .expect("Cached inputs should already be in type map!")
  30.             .clone()
  31.     };
  32.  
  33.     let mut lock = cached_inputs.lock().await;
  34.  
  35.     if lock.contains_key(input) {
  36.         Ok(lock[input].clone())
  37.     } else if input.len() > 1 {
  38.         let result = reqwest::get(
  39.             Url::parse(&format!(
  40.                 "https://maps.googleapis.com/maps/api/place/autocomplete/json?input={}&key={}",
  41.                 input,
  42.                 env!("GOOGLE_MAPS_TOKEN")
  43.             ))
  44.             .unwrap()
  45.             .as_str(),
  46.         )
  47.         .await?
  48.         .json::<FuzzyResponse>()
  49.         .await?;
  50.  
  51.         lock.insert(input.into(), result.clone());
  52.  
  53.         Ok(result)
  54.     } else {
  55.         Ok(FuzzyResponse {
  56.             predictions: vec![],
  57.         })
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment