openleadr_client/
resource.rs

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