use serde::Deserialize;
use crate::{Client, Error};
use crate::error::PowerDNSResponseError;
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde_with::skip_serializing_none]
pub struct Server {
#[serde(rename = "type")]
pub type_field: String,
pub id: String,
pub daemon_type: String,
pub version: String,
pub url: String,
pub config_url: String,
pub zones_url: String,
}
pub struct ServerClient<'a> {
api_client: &'a Client,
}
impl<'a> ServerClient<'a> {
pub fn new(api_client: &'a Client) -> Self {
ServerClient { api_client }
}
pub async fn list(&self) -> Result<Vec<Server>, Error> {
let resp = self
.api_client
.http_client
.get(format!("{}/api/v1/servers", self.api_client.base_url))
.send()
.await
.unwrap();
if resp.status().is_success() {
Ok(resp.json::<Vec<Server>>().await.unwrap())
} else {
Err(resp.json::<PowerDNSResponseError>().await?)?
}
}
pub async fn get(&self, server_id: &str) -> Result<Server, Error> {
let resp = self
.api_client
.http_client
.get(format!(
"{}/api/v1/servers/{server_id}",
self.api_client.base_url
))
.send()
.await
.unwrap();
if resp.status().is_success() {
Ok(resp.json::<Server>().await.unwrap())
} else {
Err(resp.json::<PowerDNSResponseError>().await?)?
}
}
}
#[cfg(test)]
mod tests {
use crate::client::Client;
use dotenvy::dotenv;
use std::env;
#[tokio::test]
async fn list() {
dotenv().ok();
let client = Client::new(
&env::var("PDNS_HOST").unwrap_or_else(|_| String::from("http://localhost:8081")),
&env::var("PDNS_SERVER").unwrap_or_else(|_| String::from("localhost")),
&env::var("PDNS_API_KEY").unwrap(),
);
let server_client = client.server();
let servers = server_client.list().await;
assert_eq!(servers.unwrap().len(), 1);
}
#[tokio::test]
async fn get_localhost() {
dotenv().ok();
let client = Client::new(
&env::var("PDNS_HOST").unwrap_or_else(|_| String::from("http://localhost:8081")),
&env::var("PDNS_SERVER").unwrap_or_else(|_| String::from("localhost")),
&env::var("PDNS_API_KEY").unwrap(),
);
let server_client = client.server();
let server = server_client.get("localhost").await;
assert_eq!(server.unwrap().id, "localhost");
}
}