enablebanking 0.1.0

Typed async client for the Enable Banking open banking API, generated from its OpenAPI description
Documentation
#![doc = include_str!("../README.md")]

pub mod auth;
/// The client and types generated from `spec/enablebanking-api.yaml` by `codegen`.
#[expect(
    clippy::pedantic,
    clippy::nursery,
    clippy::unwrap_used,
    missing_docs,
    unreachable_pub,
    unused_imports,
    unused_qualifications,
    rustdoc::bare_urls,
    rustdoc::broken_intra_doc_links,
    reason = "generated by progenitor from the OpenAPI description"
)]
#[cfg_attr(
    not(test),
    expect(
        clippy::missing_docs_in_private_items,
        reason = "generated by progenitor; clippy skips this lint in test builds (rust-clippy#16934)"
    )
)]
#[rustfmt::skip]
mod generated;

use std::fmt;

use progenitor_client::{ClientHooks, OperationInfo};
use reqwest::header::{AUTHORIZATION, HeaderValue};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use auth::{SignError, Signer};
pub use generated::{Client, ClientInfo, Error, ResponseValue, builder, types};

/// Base URL of the API, shared by sandbox and production applications.
pub const API_URL: &str = "https://api.enablebanking.com";

/// A monetary amount in one currency, such as a balance or a transaction amount.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Amount {
    /// ISO 4217 code of the currency, such as `EUR`.
    pub currency: String,
    /// The amount, negative for some balances.
    #[serde(with = "rust_decimal::serde::str")]
    pub amount: Decimal,
}

impl fmt::Display for Amount {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{} {}", self.amount, self.currency)
    }
}

impl ClientHooks<Signer> for Client {
    #[expect(
        clippy::unused_async_trait_impl,
        reason = "the trait declares `pre` as async"
    )]
    async fn pre<E>(
        &self,
        request: &mut reqwest::Request,
        _info: &OperationInfo,
    ) -> Result<(), Error<E>> {
        let token = self
            .inner()
            .token()
            .map_err(|error| Error::Custom(error.to_string()))?;
        #[expect(
            clippy::expect_used,
            reason = "a JWT holds only base64url characters and dots, all valid in a header"
        )]
        let value = HeaderValue::from_str(&format!("Bearer {token}"))
            .expect("a JWT holds only base64url characters and dots");
        request.headers_mut().insert(AUTHORIZATION, value);
        Ok(())
    }
}

impl Client {
    /// Every transaction of account `account_id`, following continuation keys across pages.
    ///
    /// `configure` sets the query and the PSU headers of each page request, such as a date range, a fetch strategy or the user's IP address. The bank picks the range when no dates are set, often the last 90 days.
    ///
    /// ```
    /// # async fn october(client: &enablebanking::Client, account: uuid::Uuid) -> Result<(), Box<dyn std::error::Error>> {
    /// let october = client
    ///     .all_transactions(account, |request| {
    ///         request
    ///             .date_from(jiff::civil::date(2026, 10, 1))
    ///             .date_to(jiff::civil::date(2026, 10, 31))
    ///             .psu_ip_address("203.0.113.7")
    ///     })
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns the first [`Error`] of any page, or [`Error::Custom`] when the bank sends the same continuation key twice in a row.
    #[expect(
        clippy::result_large_err,
        reason = "the same error type every generated method returns"
    )]
    pub async fn all_transactions<'a>(
        &'a self,
        account_id: Uuid,
        configure: impl Fn(builder::GetAccountTransactions<'a>) -> builder::GetAccountTransactions<'a>,
    ) -> Result<Vec<types::Transaction>, Error<types::ErrorResponse>> {
        let mut transactions = Vec::new();
        let mut continuation_key: Option<String> = None;
        loop {
            let mut request = configure(self.get_account_transactions().account_id(account_id));
            if let Some(key) = &continuation_key {
                request = request.continuation_key(key.as_str());
            }
            let page = request.send().await?.into_inner();
            transactions.extend(page.transactions);
            match page.continuation_key {
                Some(key) if key.is_empty() => return Ok(transactions),
                Some(key) if continuation_key.as_ref() == Some(&key) => {
                    return Err(Error::Custom(format!(
                        "the bank repeated continuation key {key:?}, so the listing would never end"
                    )));
                }
                Some(key) => continuation_key = Some(key),
                None => return Ok(transactions),
            }
        }
    }
}