|
| 1 | +use super::{SearchError, SearchResult}; |
| 2 | +use serde::Deserialize; |
| 3 | + |
| 4 | +#[derive(Debug, Clone)] |
| 5 | +enum DictMessage { |
| 6 | + ResultFetched(String, Response), |
| 7 | +} |
| 8 | +#[derive(Clone, Debug, Deserialize)] |
| 9 | +struct Response { |
| 10 | + // phonetic: String, |
| 11 | + // origin: String, |
| 12 | + meanings: Vec<Meaning>, |
| 13 | +} |
| 14 | + |
| 15 | +#[derive(Deserialize, Debug, Clone)] |
| 16 | +struct Meaning { |
| 17 | + #[serde(rename = "partOfSpeech")] |
| 18 | + part_of_speech: String, |
| 19 | + definitions: Vec<Defintion>, |
| 20 | +} |
| 21 | + |
| 22 | +#[derive(Deserialize, Debug, Clone)] |
| 23 | +struct Defintion { |
| 24 | + definition: String, |
| 25 | + // example: String, |
| 26 | +} |
| 27 | + |
| 28 | +impl From<&Response> for super::SearchResult { |
| 29 | + fn from(value: &Response) -> Self { |
| 30 | + Self { |
| 31 | + destination_url: String::from("n/a"), |
| 32 | + title: { |
| 33 | + // this makes me go *_* |
| 34 | + let mut o = String::new(); |
| 35 | + value |
| 36 | + .meanings |
| 37 | + .iter() |
| 38 | + .map(|m| { |
| 39 | + let mut s = String::new(); |
| 40 | + m.definitions |
| 41 | + .iter() |
| 42 | + .map(|d| d.definition.clone()) |
| 43 | + .for_each(|d| s += &d); |
| 44 | + s |
| 45 | + }) |
| 46 | + .for_each(|t| o += &t); |
| 47 | + o |
| 48 | + }, |
| 49 | + description: String::from("hugjfl"), |
| 50 | + image_url: None, |
| 51 | + } |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +pub async fn search( |
| 56 | + client: &reqwest::Client, |
| 57 | + search_text: &str, |
| 58 | +) -> Result<Vec<SearchResult>, SearchError> { |
| 59 | + let url = format!( |
| 60 | + "https://api.dictionaryapi.dev/api/v2/entries/en/{}", |
| 61 | + search_text |
| 62 | + ); |
| 63 | + |
| 64 | + let response = client |
| 65 | + .get(url) |
| 66 | + .send() |
| 67 | + .await |
| 68 | + .map_err(|e| SearchError::BadResponse(format!("failed to get response: {}", e)))?; |
| 69 | + |
| 70 | + let text = response |
| 71 | + .text() |
| 72 | + .await |
| 73 | + .map_err(|e| SearchError::BadResponse(format!("failed to get text: {}", e)))?; |
| 74 | + |
| 75 | + log::trace!("text found from dictionary: {}", text); |
| 76 | + |
| 77 | + let data: Vec<Response> = serde_json::from_str(&text) |
| 78 | + .map_err(|e| SearchError::BadResponse(format!("failed to parse from json: {}", e)))?; |
| 79 | + |
| 80 | + let data = data.iter().map(|f| f.into()).collect(); |
| 81 | + |
| 82 | + // let parsed = data.pages.into_iter().map(|result| result.into()).collect(); |
| 83 | + // log::debug!("parsed text from wikipedia: {:#?}", parsed); |
| 84 | + |
| 85 | + Ok(data) |
| 86 | +} |
0 commit comments