Skip to main content

openleadr_client/
resource.rs

1use crate::{ClientKind, ClientRef, Result};
2use chrono::{DateTime, Utc};
3use openleadr_wire::resource::{BlResourceRequest, Resource, ResourceId, ResourceRequest};
4use std::sync::Arc;
5
6/// A client
7/// for interacting with the data in a specific resource
8/// stored as a child element of a VEN on the VTN.
9///
10/// To retrieve or create a resource, refer to the [`VenClient`](crate::VenClient).
11#[derive(Debug, Clone)]
12pub struct ResourceClient<K> {
13    client: Arc<ClientRef<K>>,
14    data: Resource,
15}
16
17impl<K: ClientKind> ResourceClient<K> {
18    pub(super) fn from_resource(client: Arc<ClientRef<K>>, resource: Resource) -> Self {
19        Self {
20            client,
21            data: resource,
22        }
23    }
24
25    /// Get the resource ID
26    pub fn id(&self) -> &ResourceId {
27        &self.data.id
28    }
29
30    /// Get the time the resource was created on the VTN
31    pub fn created_date_time(&self) -> DateTime<Utc> {
32        self.data.created_date_time
33    }
34
35    /// Get the time the resource was last updated on the VTN
36    pub fn modification_date_time(&self) -> DateTime<Utc> {
37        self.data.modification_date_time
38    }
39
40    /// Read the content of the resource
41    pub fn content(&self) -> &BlResourceRequest {
42        &self.data.content
43    }
44
45    /// Modify the data of the resource.
46    /// Make sure to call [`update`](Self::update)
47    /// after your modifications to store them on the VTN.
48    pub fn content_mut(&mut self) -> &mut BlResourceRequest {
49        &mut self.data.content
50    }
51
52    /// Stores any modifications made to the resource content at the VTN
53    /// and refreshes the data stored locally with the returned VTN data
54    pub async fn update(&mut self) -> Result<()> {
55        self.data = self
56            .client
57            .put(
58                &format!("resources/{}", self.id()),
59                &ResourceRequest::BlResourceRequest(self.data.content.clone()),
60            )
61            .await?;
62        Ok(())
63    }
64
65    /// Delete the resource from the VTN
66    pub async fn delete(self) -> Result<Resource> {
67        self.client
68            .delete(&format!("resources/{}", self.id()))
69            .await
70    }
71}