From 4d45ac8ee58f6cc19ac62cb6191844377d6c13f1 Mon Sep 17 00:00:00 2001 From: Ladislav Hano Date: Wed, 2 Oct 2024 21:33:05 +0200 Subject: [PATCH] feat: rework as library --- tenor_v2rs/Cargo.lock | 35 ++++++++++++++++++++------------- tenor_v2rs/Cargo.toml | 3 +-- tenor_v2rs/src/lib.rs | 17 +++------------- tenor_v2rs/src/tenor.rs | 11 +++++++---- tenor_v2rs/src/tenor_builder.rs | 30 ++++++++++++++++++---------- tenor_v2rs/src/tenor_types.rs | 16 +++++++++++++++ 6 files changed, 68 insertions(+), 44 deletions(-) diff --git a/tenor_v2rs/Cargo.lock b/tenor_v2rs/Cargo.lock index 3634579..aab3739 100644 --- a/tenor_v2rs/Cargo.lock +++ b/tenor_v2rs/Cargo.lock @@ -26,12 +26,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "anyhow" -version = "1.0.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" - [[package]] name = "atomic-waker" version = "1.1.2" @@ -117,12 +111,6 @@ version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" -[[package]] -name = "dotenv" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" - [[package]] name = "encoding_rs" version = "0.8.33" @@ -920,12 +908,31 @@ dependencies = [ name = "tenor_v2rs" version = "0.1.0" dependencies = [ - "anyhow", - "dotenv", "form_urlencoded", "json", "regex", "reqwest", + "thiserror", +] + +[[package]] +name = "thiserror" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" +dependencies = [ + "proc-macro2", + "quote", + "syn", ] [[package]] diff --git a/tenor_v2rs/Cargo.toml b/tenor_v2rs/Cargo.toml index fbf4df1..a487414 100644 --- a/tenor_v2rs/Cargo.toml +++ b/tenor_v2rs/Cargo.toml @@ -6,12 +6,11 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -anyhow = "1.0.71" -dotenv = "0.15.0" regex = "1.9.0" json = "0.12.4" reqwest = "0.12.7" form_urlencoded = "1.2.1" +thiserror = "1.0.64" [features] DEBUG = [] diff --git a/tenor_v2rs/src/lib.rs b/tenor_v2rs/src/lib.rs index b93cf3f..d74573f 100644 --- a/tenor_v2rs/src/lib.rs +++ b/tenor_v2rs/src/lib.rs @@ -1,14 +1,3 @@ -pub fn add(left: u64, right: u64) -> u64 { - left + right -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn it_works() { - let result = add(2, 2); - assert_eq!(result, 4); - } -} +pub mod tenor; +pub mod tenor_builder; +pub mod tenor_types; \ No newline at end of file diff --git a/tenor_v2rs/src/tenor.rs b/tenor_v2rs/src/tenor.rs index 6ac9049..7cd29da 100644 --- a/tenor_v2rs/src/tenor.rs +++ b/tenor_v2rs/src/tenor.rs @@ -1,15 +1,18 @@ +use crate::tenor_types::TenorError; + use super::tenor_types::MediaFilter; use json::JsonValue; -pub fn get_gif_url(filter: MediaFilter, tenor_response: JsonValue) -> anyhow::Result> { - use anyhow::Context; - +pub fn get_gif_url(filter: MediaFilter, tenor_response: JsonValue) -> Result, TenorError> { let mut urls: Vec = Vec::new(); let results = tenor_response["results"].members(); for result in results { - let url = result["media_formats"][filter.to_string()]["url"].as_str().context("Value not found in Json")?; + let url = match result["media_formats"][filter.to_string()]["url"].as_str() { + Some(v) => v, + None => return Err(TenorError::Error("Value no found".into())) + }; urls.push(url.to_string()); } diff --git a/tenor_v2rs/src/tenor_builder.rs b/tenor_v2rs/src/tenor_builder.rs index 4f0de5a..ad0e425 100644 --- a/tenor_v2rs/src/tenor_builder.rs +++ b/tenor_v2rs/src/tenor_builder.rs @@ -2,11 +2,9 @@ use json::JsonValue; use std::collections::HashSet; -use anyhow::Error; +use crate::tenor_types::TenorError; -use crate::util::security::dotenv_var; - -use super::tenor_types::{ContentFilter, ArRange, MediaFilter}; +use crate::tenor_types::{ContentFilter, ArRange, MediaFilter}; pub struct Tenor { /// Specify the country of origin for the request. To do so, provide its two-letter ISO 3166-1 country code. @@ -34,7 +32,9 @@ pub struct Tenor { limit: Option, /// Retrieve results that start at the position /// Use a non-zero, non-empty value from next, returned by the API response, to get the next set of results - pos: Option + pos: Option, + /// Tenor api key to be used in queries + key: Option } impl Tenor { @@ -47,7 +47,8 @@ impl Tenor { ar_range: None, random: None, limit: None, - pos: None + pos: None, + key: None } } @@ -115,13 +116,19 @@ impl Tenor { self } - pub async fn search(self, query: &str) -> Result { - use anyhow::Context; + pub fn key(mut self, key: String) -> Self { + self.key = Some(key); + self + } + pub async fn search(self, query: &str) -> Result { let q: String = form_urlencoded::byte_serialize(query.as_bytes()).collect(); let base_url = "https://tenor.googleapis.com/v2/search?"; - let api_key = dotenv_var("TENORV2").context("TENORV2 key not found in the .env")?; + let api_key = match self.key { + Some(key) => key, + None => return Err(TenorError::KeyError("API key undefined".into())) + }; let mut request = format!("{base_url}q={q}&key={api_key}"); @@ -162,7 +169,10 @@ impl Tenor { request.push_str(&format!("&limit={}", self.limit.unwrap())); } - let response = reqwest::get(request).await?.text().await?; + let response = reqwest::get(request) + .await? + .text() + .await?; let response_json = json::parse(&response)?; diff --git a/tenor_v2rs/src/tenor_types.rs b/tenor_v2rs/src/tenor_types.rs index 91620e5..3baad04 100644 --- a/tenor_v2rs/src/tenor_types.rs +++ b/tenor_v2rs/src/tenor_types.rs @@ -1,6 +1,7 @@ #![allow(non_camel_case_types)] use std::fmt; +use thiserror::Error; #[derive(Debug)] pub enum ContentFilter { @@ -60,4 +61,19 @@ impl fmt::Display for ArRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } +} + +#[derive(Debug, Error)] +pub enum TenorError { + #[error("Request error")] + RequestError(#[from] reqwest::Error), + + #[error("API key error: {0}")] + KeyError(String), + + #[error("JSON error")] + JSONError(#[from] json::Error), + + #[error("Error: {0}")] + Error(String) } \ No newline at end of file