edgee_api_client/
lib.rs

1pub mod auth;
2mod upload;
3
4pub const PROD_BASEURL: &str = "https://api.edgee.app";
5
6progenitor::generate_api! {
7    spec = "openapi.json",
8    interface = Builder,
9    derives = [ schemars::JsonSchema ],
10}
11
12/// This crate's entry point
13///
14/// Use this function to build a client configured to interact with Edgee API using provided
15/// credentials
16#[bon::builder(
17    start_fn = new,
18    finish_fn = connect,
19    on(String, into),
20)]
21pub fn connect(#[builder(default = PROD_BASEURL)] baseurl: &str, api_token: String) -> Client {
22    use reqwest::header::{self, HeaderMap};
23
24    let mut default_headers = HeaderMap::new();
25
26    // if EDGEE_API_URL env var is set, redefine baseurl
27    let baseurl = std::env::var("EDGEE_API_URL").unwrap_or(baseurl.to_string());
28
29    // if EDGEE_API_TOKEN env var is set, redefine api_token
30    let api_token = std::env::var("EDGEE_API_TOKEN").unwrap_or(api_token.to_string());
31
32    let auth_value = format!("Bearer {api_token}");
33    default_headers.insert(header::AUTHORIZATION, auth_value.try_into().unwrap());
34
35    let client = reqwest::Client::builder()
36        .default_headers(default_headers)
37        .build()
38        .unwrap();
39
40    Client::new_with_client(&baseurl, client)
41}
42
43#[easy_ext::ext(ErrorExt)]
44impl Error<types::ErrorResponse> {
45    pub fn into_message(self) -> String {
46        match self {
47            Error::ErrorResponse(err) => err.error.message.clone(),
48            _ => self.to_string(),
49        }
50    }
51}
52
53#[easy_ext::ext(ResultExt)]
54impl<T> Result<T, Error<types::ErrorResponse>> {
55    pub fn api_context(self, ctx: impl std::fmt::Display) -> anyhow::Result<T> {
56        self.map_err(|err| anyhow::anyhow!("{ctx}: {}", err.into_message()))
57    }
58
59    pub fn api_with_context<F, C>(self, f: F) -> anyhow::Result<T>
60    where
61        F: FnOnce() -> C,
62        C: std::fmt::Display,
63    {
64        self.map_err(|err| {
65            let ctx = f();
66            anyhow::anyhow!("{ctx}: {}", err.into_message())
67        })
68    }
69}