From 16a484243d50db456c37c465f6cf6890af92ae0a Mon Sep 17 00:00:00 2001 From: LordMZTE Date: Sun, 26 Dec 2021 14:25:35 +0100 Subject: [PATCH] add random function --- Cargo.toml | 2 +- src/api.rs | 5 +++++ src/client.rs | 14 +++++++++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 7d39bdf..4bf6418 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "libjens" -version = "1.0.1" +version = "1.1.0" authors = ["LordMZTE "] edition = "2018" diff --git a/src/api.rs b/src/api.rs index 184948a..d2b859d 100644 --- a/src/api.rs +++ b/src/api.rs @@ -112,6 +112,11 @@ where deserializer.deserialize_any(Vis) } +#[derive(Deserialize, Debug, PartialEq, Eq, Clone)] +pub struct RandomResp { + pub meme: Meme, +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/client.rs b/src/client.rs index c4c0dea..2329057 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,4 +1,4 @@ -use crate::api::{Category, CatsResp, Meme, MemesResp, User, UsersResp}; +use crate::api::{Category, CatsResp, Meme, MemesResp, RandomResp, User, UsersResp}; use log::info; use once_cell::sync::OnceCell; use reqwest::Url; @@ -62,6 +62,7 @@ impl JMClient { })) } + /// Request the categories from the server. Result will be cached. pub async fn get_cats(&self) -> Result>, JMClientError> { self.get_api_json( &self.cache.lock().await.cats, @@ -71,6 +72,7 @@ impl JMClient { .await } + /// Request the memes from the server. Result will be cached. pub async fn get_memes(&self) -> Result>, JMClientError> { self.get_api_json(&self.cache.lock().await.memes, "memes", |r: MemesResp| { r.memes @@ -78,12 +80,22 @@ impl JMClient { .await } + /// Request the users from the server. Result will be cached. pub async fn get_users(&self) -> Result>, JMClientError> { self.get_api_json(&self.cache.lock().await.users, "users", |r: UsersResp| { r.users }) .await } + + /// Requests a random meme from the server. Result is not cached! + pub async fn get_random(&self) -> Result { + info!("Requesting random meme from server"); + + let res = self.http.get(self.endpoint.join("random")?).send().await?; + + Ok(serde_json::from_slice::(&res.bytes().await?)?.meme) + } } impl Default for JMClient { fn default() -> Self {