use crate::{agents::Agent, errors::AtomicResult, urls, Resource, Storelike, Value};
pub struct Client {
server_url: String,
store: crate::Store,
}
impl Client {
pub async fn new(server_url: &str) -> AtomicResult<Self> {
let store = crate::Store::init().await?;
store.set_base_url(server_url);
store.populate().await?;
Ok(Self {
server_url: server_url.to_string(),
store,
})
}
pub fn server_url(&self) -> &str {
&self.server_url
}
pub fn store(&self) -> &crate::Store {
&self.store
}
pub async fn new_agent(&self, name: &str) -> AtomicResult<Agent> {
let agent = self.store.create_agent(Some(name)).await?;
self.store.set_default_agent(agent.clone());
Ok(agent)
}
pub async fn new_drive(&self, agent: &Agent, name: &str) -> AtomicResult<String> {
self.store.set_default_agent(agent.clone());
let mut drive = Resource::new("did:ad:placeholder".into());
drive.set_unsafe(
urls::IS_A.into(),
Value::ResourceArray(vec![urls::DRIVE.into()]),
)?;
drive.set_name(name)?;
drive.set_unsafe(
urls::WRITE.into(),
Value::ResourceArray(vec![agent.subject.to_string().into()]),
)?;
drive.set_unsafe(
urls::READ.into(),
Value::ResourceArray(vec![agent.subject.to_string().into()]),
)?;
drive.save_remote(&self.store).await
}
pub async fn new_public_drive(&self, agent: &Agent, name: &str) -> AtomicResult<String> {
self.store.set_default_agent(agent.clone());
let mut drive = Resource::new("did:ad:placeholder".into());
drive.set_unsafe(
urls::IS_A.into(),
Value::ResourceArray(vec![urls::DRIVE.into()]),
)?;
drive.set_name(name)?;
drive.set_unsafe(
urls::WRITE.into(),
Value::ResourceArray(vec![agent.subject.to_string().into()]),
)?;
drive.set_unsafe(
urls::READ.into(),
Value::ResourceArray(vec![urls::PUBLIC_AGENT.into()]),
)?;
drive.save_remote(&self.store).await
}
pub fn new_resource(&self, parent: &str) -> AtomicResult<Resource> {
let mut resource = Resource::new("did:ad:placeholder".into());
resource.set_unsafe(urls::PARENT.into(), Value::AtomicUrl(parent.into()))?;
Ok(resource)
}
pub async fn get_resource(&self, subject: &str) -> AtomicResult<Resource> {
let response = crate::client::fetch_resource(
subject,
&self.store,
self.store.get_default_agent().ok().as_ref(),
)
.await?;
Ok(response.to_single())
}
}