use derive_builder::Builder;
use maybe_async::maybe_async;
use serde::Deserialize;
use serde_json::json;
use crate::{
config::Config,
error::Result,
http,
http::HttpClient,
model::{
authenticate::{Authenticate, AuthenticatePayload},
cancel::{Cancel, CancelPayload},
collect::{Collect, CollectPayload},
sign::{Sign, SignPayload},
},
};
#[derive(Builder, Clone, Debug)]
pub struct BankID {
pub(crate) client: Box<dyn http::HttpClient>,
}
impl BankID {
pub fn new(config: Config) -> Self {
let client =
http::client::Client::try_from(config).expect("Could not create a client from the supplied config");
Self {
client: Box::new(client),
}
}
#[maybe_async]
pub async fn authenticate(&self, payload: AuthenticatePayload) -> Result<Authenticate> {
let result = self.client.post("/auth", &json!(payload)).await?;
self.convert_result(&result)
}
#[maybe_async]
pub async fn sign(&self, payload: SignPayload) -> Result<Sign> {
let result = self.client.post("/sign", &json!(payload)).await?;
self.convert_result(&result)
}
#[maybe_async]
pub async fn collect(&self, payload: CollectPayload) -> Result<Collect> {
let result = self.client.post("/collect", &json!(payload)).await?;
self.convert_result(&result)
}
#[maybe_async]
pub async fn cancel(&self, payload: CancelPayload) -> Result<Cancel> {
let result = self.client.post("/cancel", &json!(payload)).await?;
self.convert_result(&result)
}
fn convert_result<'a, T: Deserialize<'a>>(&self, input: &'a str) -> Result<T> {
serde_json::from_str::<T>(input).map_err(Into::into)
}
}