taskr/src/gitlab.rs
2024-03-19 12:07:37 -05:00

49 lines
1.3 KiB
Rust

use crate::result::Result;
use reqwest::{
header::{HeaderMap, HeaderValue},
Client, Url,
};
use reqwest_middleware::ClientWithMiddleware;
use serde::Deserialize;
pub struct GitLab {
url: Url,
client: ClientWithMiddleware,
}
#[derive(Deserialize, Debug)]
pub struct User {
pub id: u64,
pub username: String,
pub email: String,
pub name: String,
pub state: String,
pub locked: bool,
pub created_at: String,
pub public_email: String,
}
impl GitLab {
pub fn try_new(url: &str, token: &str) -> Result<Self> {
let url = Url::parse(&format!("{}{}", url.trim_end_matches('/'), "/"))?;
let mut headers = HeaderMap::new();
headers.insert("PRIVATE-TOKEN", HeaderValue::from_str(token)?);
headers.insert("content-type", HeaderValue::from_str("application/json")?);
headers.insert("accepts", HeaderValue::from_str("application/json")?);
let base_client = Client::builder().default_headers(headers).build()?;
let client = crate::client::wrap_with_middleware(base_client);
Ok(Self { url, client })
}
pub fn url(&self, path: &str) -> Result<Url> {
Ok(self.url.join(path.trim_start_matches('/'))?)
}
pub async fn me(&self) -> Result<User> {
let res = self.client.get(self.url("/user")?).send().await?;
Ok(res.json().await?)
}
}