88 lines
2.1 KiB
Rust
88 lines
2.1 KiB
Rust
use crate::config::OpenProjectConfig;
|
|
use crate::error::GeneralError;
|
|
use crate::openproject::work::{WorkPackage, WorkPackageWriter};
|
|
use reqwest::Response;
|
|
use serde::Deserialize;
|
|
|
|
#[derive(Deserialize, Debug)]
|
|
pub(crate) struct Error {
|
|
pub(crate) description: String,
|
|
}
|
|
|
|
impl From<reqwest::Error> for Error {
|
|
fn from(value: reqwest::Error) -> Self {
|
|
Error {
|
|
description: format!("Error while connecting to openproject instance: {}", value),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<Error> for GeneralError {
|
|
fn from(value: Error) -> GeneralError {
|
|
GeneralError {
|
|
description: value.description,
|
|
}
|
|
}
|
|
}
|
|
|
|
pub(crate) struct Client {
|
|
pub(crate) base_url: String,
|
|
pub(crate) token: String,
|
|
}
|
|
|
|
pub async fn handle_response_status<T: for<'de> serde::Deserialize<'de>>(
|
|
response: Response,
|
|
error_message: &str,
|
|
) -> Result<T, Error> {
|
|
if !response.status().is_success() {
|
|
let status = response.status().to_string().clone();
|
|
let content = response
|
|
.text()
|
|
.await
|
|
.unwrap_or_else(|_| "Impossible to decode".into())
|
|
.clone();
|
|
|
|
return Err(Error {
|
|
description: format!(
|
|
"{}, status: {}, content: {}",
|
|
error_message, status, content
|
|
),
|
|
});
|
|
}
|
|
|
|
let t = response.json().await?;
|
|
|
|
Ok(t)
|
|
}
|
|
|
|
impl Client {
|
|
pub fn from_config(config: &OpenProjectConfig) -> Client {
|
|
Client {
|
|
base_url: config.base_url.clone(),
|
|
token: config.token.clone(),
|
|
}
|
|
}
|
|
|
|
pub async fn create_work_package(
|
|
&self,
|
|
work_package: &WorkPackageWriter,
|
|
project_id: &String,
|
|
) -> Result<WorkPackage, Error> {
|
|
let client = reqwest::Client::new();
|
|
|
|
let work_package: WorkPackage = client
|
|
.post(format!(
|
|
"{}/api/v3/projects/{}/work_packages",
|
|
self.base_url, project_id
|
|
))
|
|
.basic_auth("apikey", Some(&self.token))
|
|
.json(&work_package)
|
|
.send()
|
|
.await?
|
|
.json()
|
|
.await?;
|
|
|
|
Ok(work_package)
|
|
}
|
|
}
|