vortaroboto

Log | Files | Refs | README

requests.rs (2079B)


      1 use futures::prelude::*;
      2 use serde::{Deserialize, de::DeserializeOwned};
      3 use cached::proc_macro::cached;
      4 
      5 const TROVI_URL: &'static str = "http://www.simplavortaro.org/api/v1/trovi";
      6 const VORTO_URL: &'static str = "http://www.simplavortaro.org/api/v1/vorto";
      7 
      8 #[derive(Deserialize, Debug, Clone)]
      9 pub struct Vortpartoj {
     10     pub vorto: Option<String>,
     11     pub parto: String,
     12 }
     13 
     14 #[derive(Deserialize, Debug, Clone)]
     15 pub struct Vortfarado {
     16     pub partoj: Vec<Vortpartoj>,
     17     pub rezulto: String,
     18 }
     19 
     20 #[derive(Deserialize, Debug, Clone)]
     21 pub struct Traduko {
     22     pub kodo: String,
     23     pub vorto: Option<String>,
     24     pub lingvo: String,
     25     pub traduko: String,
     26 }
     27 
     28 #[derive(Deserialize, Debug, Clone)]
     29 pub struct Trovo {
     30     pub malpreciza: Vec<String>,
     31     pub vortfarado: Vec<Vortfarado>,
     32     pub preciza: Vec<String>,
     33     pub tradukoj: Vec<Traduko>,
     34 }
     35 
     36 #[derive(Deserialize, Debug, Clone)]
     37 pub struct Ekzemplo {
     38     pub ekzemplo: String,
     39     pub fonto: Option<String>,
     40 }
     41 
     42 #[derive(Deserialize, Debug, Clone)]
     43 pub struct Difino {
     44     pub difino: String,
     45     pub ekzemploj: Vec<Ekzemplo>,
     46     pub tradukoj: Vec<Traduko>,
     47 }
     48 
     49 #[derive(Deserialize, Debug, Clone)]
     50 pub struct Vorto {
     51     pub difinoj: Vec<Difino>,
     52     pub vorto: String,
     53 }
     54 
     55 
     56 async fn req<T>(url: &str, vorto: String) -> Result<T, String>
     57 where
     58     T: DeserializeOwned,
     59 {
     60     reqwest::get(format!("{}/{}", url, vorto.to_lowercase()))
     61         .and_then(|j| j.json::<T>())
     62         .map_err(|e| e.to_string())
     63         .await
     64 }
     65 
     66 fn prepare_word(vorto: String) -> String {
     67     vorto
     68         .to_lowercase()
     69         .chars()
     70         .filter(|c| c.is_alphabetic())
     71         .collect()
     72 }
     73 
     74 macro_rules! q {
     75     ($finternal:ident, $fname:ident, $t:ty, $url:expr) => {
     76         #[cached(size=200)]
     77         async fn $finternal(vorto: String) -> Result<$t, String> {
     78             req::<$t>($url, vorto).await
     79         }
     80 
     81         pub async fn $fname(vorto: String) -> Result<$t, String> {
     82             $finternal(prepare_word(vorto)).await
     83         }
     84     };
     85 }
     86 
     87 q! { t_int, trovu, Vorto, VORTO_URL }
     88 q! { d_int, difinu, Trovo, TROVI_URL }