Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use crate::TypeMapKey;
- use reqwest::Url;
- use serde::{Deserialize, Serialize};
- use serenity::prelude::*;
- use std::collections::HashMap;
- use std::sync::Arc;
- #[derive(Debug, Clone, Serialize, Deserialize)]
- pub struct FuzzyResponse {
- pub predictions: Vec<FuzzyLocation>,
- }
- #[derive(Debug, Clone, Serialize, Deserialize)]
- pub struct FuzzyLocation {
- pub description: String,
- }
- pub struct CachedInputs;
- impl TypeMapKey for CachedInputs {
- type Value = Arc<Mutex<HashMap<String, FuzzyResponse>>>;
- }
- pub async fn fuzzy_search(ctx: &Context, input: &str) -> anyhow::Result<FuzzyResponse> {
- let cached_inputs = {
- let data = ctx.data.read().await;
- data.get::<CachedInputs>()
- .expect("Cached inputs should already be in type map!")
- .clone()
- };
- let mut lock = cached_inputs.lock().await;
- if lock.contains_key(input) {
- Ok(lock[input].clone())
- } else if input.len() > 1 {
- let result = reqwest::get(
- Url::parse(&format!(
- "https://maps.googleapis.com/maps/api/place/autocomplete/json?input={}&key={}",
- input,
- env!("GOOGLE_MAPS_TOKEN")
- ))
- .unwrap()
- .as_str(),
- )
- .await?
- .json::<FuzzyResponse>()
- .await?;
- lock.insert(input.into(), result.clone());
- Ok(result)
- } else {
- Ok(FuzzyResponse {
- predictions: vec![],
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment