use url::Url;
use crate::{
auth::{
options::{Options, SerializableOptions},
response::GrantResponse,
},
send_and_translate_response, Deepgram,
};
pub mod options;
pub mod response;
#[derive(Debug, Clone)]
pub struct Auth<'a>(&'a Deepgram);
impl Deepgram {
pub fn auth(&self) -> Auth<'_> {
self.into()
}
}
impl<'a> From<&'a Deepgram> for Auth<'a> {
fn from(deepgram: &'a Deepgram) -> Self {
Self(deepgram)
}
}
impl Auth<'_> {
pub async fn grant(&self, options: Option<&Options>) -> crate::Result<GrantResponse> {
let url = self.grant_url()?;
let request = if let Some(opts) = options {
self.0
.client
.post(url)
.json(&SerializableOptions::from(opts))
} else {
self.0.client.post(url).json(&serde_json::json!({}))
};
send_and_translate_response(request).await
}
fn grant_url(&self) -> crate::Result<Url> {
self.0.api_url("v1/auth/grant")
}
}
#[cfg(test)]
mod tests {
use crate::Deepgram;
#[test]
fn urls_default_base() {
let dg = Deepgram::new("token").unwrap();
assert_eq!(
dg.auth().grant_url().unwrap().as_str(),
"https://api.deepgram.com/v1/auth/grant"
);
}
#[test]
fn urls_custom_base() {
let dg = Deepgram::with_base_url("http://deepgram.internal").unwrap();
assert_eq!(
dg.auth().grant_url().unwrap().as_str(),
"http://deepgram.internal/v1/auth/grant"
);
}
#[test]
fn urls_custom_base_with_path_prefix() {
let dg = Deepgram::with_base_url("http://gateway/deepgram/").unwrap();
assert_eq!(
dg.auth().grant_url().unwrap().as_str(),
"http://gateway/deepgram/v1/auth/grant"
);
}
}