sandwichmeister/src/directus/client.rs
2025-08-06 17:24:33 +02:00

61 lines
1.5 KiB
Rust

use std::error::Error;
use reqwest::header::{self, HeaderMap};
use crate::config::ConfigDirectus;
use super::model::{DirectusResponse, Ingredient, RawSandwich, Sandwich};
pub struct DirectusClient {
config: ConfigDirectus,
client: reqwest::Client,
}
impl DirectusClient {
pub fn new(config: ConfigDirectus) -> Self {
let mut headers = HeaderMap::new();
let mut auth_value =
header::HeaderValue::from_str(&format!("Bearer {}", config.token.clone())).unwrap();
auth_value.set_sensitive(true);
headers.insert(header::AUTHORIZATION, auth_value);
let client = reqwest::Client::builder()
.default_headers(headers)
.build()
.expect("Failed to construct Directus Client");
DirectusClient { config, client }
}
pub async fn get_ingredients(&self) -> Result<Vec<Ingredient>, Box<dyn Error>> {
let response = self
.client
.get(format!("{}/items/Ingredients", self.config.url))
.send()
.await?
.json::<DirectusResponse<Vec<Ingredient>>>()
.await?;
Ok(response.data)
}
pub async fn get_sandwiches(&self) -> Result<Vec<Sandwich>, Box<dyn Error>> {
let response = self
.client
.get(format!("{}/items/Sandwiches", self.config.url))
.send()
.await?
.json::<DirectusResponse<Vec<RawSandwich>>>()
.await?;
let ingredients = self.get_ingredients().await?;
Ok(
response
.data
.iter()
.map(|s| s.resolve(&ingredients))
.collect::<Vec<Sandwich>>(),
)
}
}