slack_rust/
http_client.rs

1//! HTTP client for Slack WEB API.
2
3use crate::error::Error;
4use async_trait::async_trait;
5#[cfg(test)]
6use mockall::automock;
7use serde::{Deserialize, Serialize};
8use serde_with::skip_serializing_none;
9
10#[cfg_attr(test, automock)]
11#[async_trait]
12pub trait SlackWebAPIClient: Sync + Send {
13    async fn post_json(&self, url: &str, body: &str, token: &str) -> Result<String, Error>;
14    async fn post(&self, url: &str, token: &str) -> Result<String, Error>;
15}
16
17pub type Client = surf::Client;
18
19#[async_trait]
20impl SlackWebAPIClient for Client {
21    /// Send a post request to the slack api.
22    async fn post_json(&self, url: &str, body: &str, token: &str) -> Result<String, Error> {
23        let check_url = url::Url::parse(url)?;
24
25        Ok(self
26            .post(check_url)
27            .header("Authorization", format!("Bearer {}", token))
28            .header("Content-type", "application/json; charset=utf-8")
29            .body(body)
30            .await?
31            .body_string()
32            .await?)
33    }
34
35    /// Send a post request to the slack api.
36    async fn post(&self, url: &str, token: &str) -> Result<String, Error> {
37        let check_url = url::Url::parse(url)?;
38
39        Ok(self
40            .post(check_url)
41            .header("Authorization", format!("Bearer {}", token))
42            .await?
43            .body_string()
44            .await?)
45    }
46}
47
48/// Returns the slack api url for each method.
49pub fn get_slack_url(method: &str) -> String {
50    format!("https://slack.com/api/{}", method)
51}
52
53/// Provides a default `surf` client to give to the API functions to send requests.
54pub fn default_client() -> Client {
55    surf::Client::new()
56}
57
58/// Slack default response.
59#[skip_serializing_none]
60#[derive(Deserialize, Serialize, Debug, Default, PartialEq)]
61pub struct DefaultResponse {
62    pub ok: bool,
63    pub error: Option<String>,
64    pub response_metadata: Option<ResponseMetadata>,
65}
66
67/// Metadata.
68#[skip_serializing_none]
69#[derive(Deserialize, Serialize, Debug, Default, PartialEq)]
70pub struct ResponseMetadata {
71    pub next_cursor: Option<String>,
72    pub messages: Option<Vec<String>>,
73    pub warnings: Option<Vec<String>>,
74}