hackmd_rs/
context.rs

1use reqwest::Client;
2use serde::{de::DeserializeOwned, Serialize};
3
4use crate::error::{Error, Result};
5
6const HACKMD_API_BASE_URL: &str = "https://api.hackmd.io/v1";
7
8pub struct Context {
9    pub(crate) bearer: String,
10    pub(crate) client: Client,
11}
12
13impl Context {
14    pub fn new(token: &str) -> Context {
15        let bearer = Self::make_bearer(token);
16        let client = reqwest::Client::new();
17
18        Context { bearer, client }
19    }
20
21    pub(crate) async fn get<T>(&self, path: &str) -> Result<T>
22    where
23        T: DeserializeOwned,
24    {
25        self.client
26            .get(Context::make_url(path))
27            .header("Authorization", &self.bearer)
28            .send()
29            .await?
30            .json()
31            .await
32            .map_err(Error::from)
33    }
34
35    pub(crate) async fn patch<T>(&self, path: &str, payload: &T) -> Result<()>
36    where
37        T: Serialize,
38    {
39        self.client
40            .patch(Context::make_url(path))
41            .header("Authorization", &self.bearer)
42            .json(payload)
43            .send()
44            .await
45            .map(drop)
46            .map_err(Error::from)
47    }
48
49    fn make_bearer(token: &str) -> String {
50        format!("Bearer {token}")
51    }
52
53    pub(crate) fn make_url(route: &str) -> String {
54        format!("{HACKMD_API_BASE_URL}/{route}")
55    }
56}