use std::fmt;
use crate::api::ApiResult;
use crate::latest;
use crate::show::Show;
#[derive(Debug)]
pub(crate) struct Realm {
api: super::Api,
path: String,
}
impl Realm {
pub(crate) fn new(api: super::Api) -> Self {
let path = String::from("/realms");
Self { api, path }
}
pub(crate) fn create(
&self,
name: impl AsRef<str>,
realm: latest::RealmTypeCreate,
) -> Result<String, anyhow::Error> {
let create = latest::RealmCreate {
name: name.as_ref().to_owned(),
realm,
};
let realm = self
.api
.post::<_, _, latest::Realm>(&self.path, create)
.map(Show::show)?;
Ok(realm)
}
pub(crate) fn delete(&self, realm: impl AsRef<str>) -> Result<String, anyhow::Error> {
let realm = realm.as_ref();
log::debug!("sending delete realm");
let path = format!("{}/{}", self.path, realm);
self.api.del::<_, _, &str, &str, ()>(path, &[])?;
Ok(String::new())
}
pub(crate) fn list(&self) -> Result<String, anyhow::Error> {
self.api.get::<_, latest::Realms>(&self.path).map(|v| {
v.realms
.iter()
.map(|v| v.name.clone())
.collect::<Vec<_>>()
.join("\n")
})
}
pub(crate) fn show(&self, realm: impl AsRef<str>) -> Result<String, anyhow::Error> {
self.get_realm(realm.as_ref()).map(Show::show)
}
fn get_realm(&self, realm: impl fmt::Display) -> ApiResult<latest::Realm> {
let path = format!("{}/{}", self.path, realm);
self.api.get(path)
}
}