qstash_rs/client/
mod.rs

1//! # Client module.
2//! This module contains the main struct you will use to interact with the QStash API.
3//! It is initialized with a token and optionally a base url and a version.
4//! The default base url is `https://qstash.upstash.io`.
5
6pub mod dead_letter_queue;
7mod error;
8pub mod events;
9pub mod messages;
10pub mod publish;
11mod request;
12
13use error::*;
14pub use request::*;
15
16use reqwest::{header, Url};
17
18/// The version of the QStash API to use.
19/// The default is V2.
20pub enum Version {
21    V1,
22    V2,
23}
24
25/// The QStash client.
26/// It is initialized with a token and optionally a base url and a version.
27/// The default base url is `https://qstash.upstash.io`.
28/// The default version is V2.
29pub struct Client {
30    pub http: reqwest::Client,
31    base_url: Url,
32    version: String,
33}
34
35impl Client {
36    /// Initialize a new QStash client.
37    /// The token is required.
38    /// The base url and version are optional.
39    pub fn new(
40        token: &str,
41        base_url: Option<&str>,
42        version: Option<Version>,
43    ) -> Result<Client, QStashError> {
44        // intialize default headers
45        let mut value = match header::HeaderValue::from_str(&format!("Bearer {token}")) {
46            Ok(v) => v,
47            Err(e) => {
48                let formated_string = e.to_string();
49                tracing::error!(formated_string);
50                return Err(QStashError::TokenError);
51            }
52        };
53
54        value.set_sensitive(true);
55        let mut headers = header::HeaderMap::new();
56        headers.insert(header::AUTHORIZATION, value);
57
58        // initialize reqwest client
59        let http = match reqwest::Client::builder().default_headers(headers).build() {
60            Ok(c) => c,
61            Err(e) => {
62                let formated_string = e.to_string();
63                tracing::error!(formated_string);
64                return Err(QStashError::ReqwestError);
65            }
66        };
67
68        let version = match version.unwrap_or(Version::V2) {
69            Version::V1 => String::from("v1"),
70            Version::V2 => String::from("v2"),
71        };
72
73        // parsing url from the provided value or use default
74        let url = match Url::parse(base_url.unwrap_or("https://qstash.upstash.io")) {
75            Ok(u) => u,
76            Err(e) => {
77                let formated_string = e.to_string();
78                tracing::error!(formated_string);
79                return Err(QStashError::InvalidUrl);
80            }
81        };
82
83        Ok(Self {
84            http,
85            base_url: url,
86            version,
87        })
88    }
89}