iop_client/
lib.rs

1use constants::caches;
2use deadpool_redis::{redis::cmd, Runtime};
3use log::info;
4use reqwest::Client;
5
6mod constants;
7mod core;
8mod model;
9mod photobank;
10mod product_category;
11mod product_country;
12mod product_group;
13mod token;
14
15#[derive(Clone)]
16pub struct IopClient {
17    appid: String,
18    app_secret: String,
19    pool: deadpool_redis::Pool,
20    client: Client,
21}
22
23impl IopClient {
24    /// Creates a new instance of `IopClient`.
25    ///
26    /// This function initializes an `IopClient` with the specified application ID,
27    /// application secret, and Redis address. It attempts to create a connection pool
28    /// to the Redis server using the provided address and verifies the connection by
29    /// setting a test key. If the connection is successful, an `IopClient` object is
30    /// returned; otherwise, the function panics with an error message.
31    ///
32    /// # Arguments
33    ///
34    /// * `appid` - The application ID for the client.
35    /// * `app_secret` - The secret key associated with the application ID.
36    /// * `redis_addr` - The address of the Redis server to connect to.
37    ///
38    /// # Returns
39    ///
40    /// A `Result` containing the `IopClient` instance if successful, or an error if the
41    /// Redis connection could not be established.
42    pub async fn new(
43        appid: String,
44        app_secret: String,
45        redis_addr: String,
46    ) -> Result<Self, Box<dyn std::error::Error>> {
47        let cfg = deadpool_redis::Config::from_url(redis_addr);
48        let pool = match cfg.create_pool(Some(Runtime::Tokio1)) {
49            Ok(pool) => pool,
50            Err(err) => {
51                panic!("Failed to create redis pool: {err}")
52            }
53        };
54
55        match pool.get().await {
56            Ok(mut conn) => {
57                match cmd("SETEX")
58                    .arg("PING")
59                    .arg(caches::FIVE_MINUTE_IN_SECONDS)
60                    .arg("pong")
61                    .query_async::<()>(&mut conn)
62                    .await
63                {
64                    Ok(_) => {
65                        info!("Redis connected");
66                    }
67                    Err(err) => {
68                        panic!("Failed to connect to redis: {err}")
69                    }
70                }
71            }
72            Err(err) => {
73                panic!("Failed to connect to redis: {err}")
74            }
75        };
76
77        Ok(IopClient {
78            appid,
79            app_secret,
80            pool,
81            client: Client::new(),
82        })
83    }
84}