use serde::{Deserialize, Serialize};
use crate::{WakapiClient, WakapiError};
use super::commit::{CommitDetails, CommitProjectDetails};
pub struct CommitsParams {
url: CommitsParamsUrl,
params: CommitsParamsParams,
}
struct CommitsParamsUrl {
project: String,
}
#[derive(Serialize, Default)]
struct CommitsParamsParams {
author: Option<String>,
branch: Option<String>,
page: Option<usize>,
}
impl CommitsParams {
pub fn new(project: &str) -> CommitsParams {
CommitsParams {
url: CommitsParamsUrl {
project: project.to_string(),
},
params: CommitsParamsParams {
author: None,
branch: None,
page: None,
},
}
}
pub fn author(mut self, author: &str) -> CommitsParams {
self.params.author = Some(author.to_string());
self
}
pub fn branch(mut self, branch: &str) -> CommitsParams {
self.params.branch = Some(branch.to_string());
self
}
pub fn page(mut self, page: usize) -> CommitsParams {
self.params.page = Some(page);
self
}
}
#[derive(Deserialize, Debug)]
pub struct Commits {
pub commits: Vec<CommitDetails>,
pub author: Option<String>,
pub page: usize,
pub next_page: Option<usize>,
pub next_page_url: Option<String>,
pub prev_page: Option<usize>,
pub prev_page_url: Option<String>,
pub branch: String,
pub project: CommitProjectDetails,
pub status: String,
pub total: usize,
pub total_pages: usize,
}
impl Commits {
#[cfg(feature = "blocking")]
pub fn fetch(client: &WakapiClient, params: CommitsParams) -> Result<Self, WakapiError> {
let url = client.build_url(
format!(
"/api/v1/users/:user/projects/{}/commits",
¶ms.url.project
)
.as_str(),
Some(serde_url_params::to_string(¶ms.params)?),
);
let response = reqwest::blocking::Client::new()
.get(&url)
.header("Authorization", client.get_auth_header())
.send()?;
if response.status().is_success() {
let body = response.json::<Commits>()?;
Ok(body)
} else {
let error = response.json::<crate::error::ErrorMessage>()?;
Err(WakapiError::ResponseError(error))
}
}
#[cfg(not(feature = "blocking"))]
pub async fn fetch(client: &WakapiClient, params: CommitsParams) -> Result<Self, WakapiError> {
let url = client.build_url(
format!(
"/api/v1/users/:user/projects/{}/commits",
¶ms.url.project
)
.as_str(),
Some(serde_url_params::to_string(¶ms.params)?),
);
let response = reqwest::Client::new()
.get(&url)
.header("Authorization", client.get_auth_header())
.send()
.await?;
if response.status().is_success() {
let body = response.json::<Commits>().await?;
Ok(body)
} else {
let error = response.json::<crate::error::ErrorMessage>().await?;
Err(WakapiError::ResponseError(error))
}
}
}