rippling_api/
custom_objects.rs

1use anyhow::Result;
2
3use crate::Client;
4#[derive(Clone, Debug)]
5pub struct CustomObjects {
6    pub client: Client,
7}
8
9impl CustomObjects {
10    #[doc(hidden)]
11    pub fn new(client: Client) -> Self {
12        Self { client }
13    }
14
15    #[doc = "List custom objects\n\nA List of custom objects\n- Requires: `API Tier 1`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_custom_objects_list_stream() -> anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let mut custom_objects = client.custom_objects();\n    let mut stream = custom_objects.list_stream();\n    loop {\n        match stream.try_next().await {\n            Ok(Some(item)) => {\n                println!(\"{:?}\", item);\n            }\n            Ok(None) => {\n                break;\n            }\n            Err(err) => {\n                return Err(err.into());\n            }\n        }\n    }\n\n    Ok(())\n}\n```"]
16    #[tracing::instrument]
17    pub async fn list<'a>(
18        &'a self,
19        cursor: Option<String>,
20    ) -> Result<crate::types::ListCustomObjectsResponse, crate::types::error::Error> {
21        let mut req = self.client.client.request(
22            http::Method::GET,
23            format!("{}/{}", self.client.base_url, "custom-objects"),
24        );
25        req = req.bearer_auth(&self.client.token);
26        let mut query_params = vec![];
27        if let Some(p) = cursor {
28            query_params.push(("cursor", p));
29        }
30
31        req = req.query(&query_params);
32        let resp = req.send().await?;
33        let status = resp.status();
34        if status.is_success() {
35            let text = resp.text().await.unwrap_or_default();
36            serde_json::from_str(&text).map_err(|err| {
37                crate::types::error::Error::from_serde_error(
38                    format_serde_error::SerdeError::new(text.to_string(), err),
39                    status,
40                )
41            })
42        } else {
43            let text = resp.text().await.unwrap_or_default();
44            Err(crate::types::error::Error::Server {
45                body: text.to_string(),
46                status,
47            })
48        }
49    }
50
51    #[doc = "List custom objects\n\nA List of custom objects\n- Requires: `API Tier 1`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_custom_objects_list_stream() -> anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let mut custom_objects = client.custom_objects();\n    let mut stream = custom_objects.list_stream();\n    loop {\n        match stream.try_next().await {\n            Ok(Some(item)) => {\n                println!(\"{:?}\", item);\n            }\n            Ok(None) => {\n                break;\n            }\n            Err(err) => {\n                return Err(err.into());\n            }\n        }\n    }\n\n    Ok(())\n}\n```"]
52    #[tracing::instrument]
53    #[cfg(not(feature = "js"))]
54    pub fn list_stream<'a>(
55        &'a self,
56    ) -> impl futures::Stream<Item = Result<crate::types::CustomObject, crate::types::error::Error>>
57           + Unpin
58           + '_ {
59        use futures::{StreamExt, TryFutureExt, TryStreamExt};
60
61        use crate::types::paginate::Pagination;
62        self.list(None)
63            .map_ok(move |result| {
64                let items = futures::stream::iter(result.items().into_iter().map(Ok));
65                let next_pages = futures::stream::try_unfold(
66                    (None, result),
67                    move |(prev_page_token, new_result)| async move {
68                        if new_result.has_more_pages()
69                            && !new_result.items().is_empty()
70                            && prev_page_token != new_result.next_page_token()
71                        {
72                            async {
73                                let mut req = self.client.client.request(
74                                    http::Method::GET,
75                                    format!("{}/{}", self.client.base_url, "custom-objects"),
76                                );
77                                req = req.bearer_auth(&self.client.token);
78                                let mut request = req.build()?;
79                                request = new_result.next_page(request)?;
80                                let resp = self.client.client.execute(request).await?;
81                                let status = resp.status();
82                                if status.is_success() {
83                                    let text = resp.text().await.unwrap_or_default();
84                                    serde_json::from_str(&text).map_err(|err| {
85                                        crate::types::error::Error::from_serde_error(
86                                            format_serde_error::SerdeError::new(
87                                                text.to_string(),
88                                                err,
89                                            ),
90                                            status,
91                                        )
92                                    })
93                                } else {
94                                    let text = resp.text().await.unwrap_or_default();
95                                    Err(crate::types::error::Error::Server {
96                                        body: text.to_string(),
97                                        status,
98                                    })
99                                }
100                            }
101                            .map_ok(|result: crate::types::ListCustomObjectsResponse| {
102                                Some((
103                                    futures::stream::iter(result.items().into_iter().map(Ok)),
104                                    (new_result.next_page_token(), result),
105                                ))
106                            })
107                            .await
108                        } else {
109                            Ok(None)
110                        }
111                    },
112                )
113                .try_flatten();
114                items.chain(next_pages)
115            })
116            .try_flatten_stream()
117            .boxed()
118    }
119
120    #[doc = "Create a new custom object\n\nCreate a new custom object\n\n```rust,no_run\nasync fn \
121             example_custom_objects_create() -> anyhow::Result<()> {\n    let client = \
122             rippling_api::Client::new_from_env();\n    let result: \
123             rippling_api::types::CustomObject = client\n        .custom_objects()\n        \
124             .create(&rippling_api::types::CreateCustomObjectsRequestBody {\n            name: \
125             Some(\"some-string\".to_string()),\n            description: \
126             Some(\"some-string\".to_string()),\n            category: \
127             Some(\"some-string\".to_string()),\n        })\n        .await?;\n    \
128             println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
129    #[tracing::instrument]
130    pub async fn create<'a>(
131        &'a self,
132        body: &crate::types::CreateCustomObjectsRequestBody,
133    ) -> Result<crate::types::CustomObject, crate::types::error::Error> {
134        let mut req = self.client.client.request(
135            http::Method::POST,
136            format!("{}/{}", self.client.base_url, "custom-objects"),
137        );
138        req = req.bearer_auth(&self.client.token);
139        req = req.json(body);
140        let resp = req.send().await?;
141        let status = resp.status();
142        if status.is_success() {
143            let text = resp.text().await.unwrap_or_default();
144            serde_json::from_str(&text).map_err(|err| {
145                crate::types::error::Error::from_serde_error(
146                    format_serde_error::SerdeError::new(text.to_string(), err),
147                    status,
148                )
149            })
150        } else {
151            let text = resp.text().await.unwrap_or_default();
152            Err(crate::types::error::Error::Server {
153                body: text.to_string(),
154                status,
155            })
156        }
157    }
158
159    #[doc = "Retrieve a specific custom object\n\nRetrieve a specific custom \
160             object\n\n**Parameters:**\n\n- `custom_object_api_name: &'astr` \
161             (required)\n\n```rust,no_run\nasync fn example_custom_objects_get() -> \
162             anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let \
163             result: rippling_api::types::CustomObject = \
164             client.custom_objects().get(\"some-string\").await?;\n    println!(\"{:?}\", \
165             result);\n    Ok(())\n}\n```"]
166    #[tracing::instrument]
167    pub async fn get<'a>(
168        &'a self,
169        custom_object_api_name: &'a str,
170    ) -> Result<crate::types::CustomObject, crate::types::error::Error> {
171        let mut req = self.client.client.request(
172            http::Method::GET,
173            format!(
174                "{}/{}",
175                self.client.base_url,
176                "custom-objects/{custom_object_api_name}"
177                    .replace("{custom_object_api_name}", custom_object_api_name)
178            ),
179        );
180        req = req.bearer_auth(&self.client.token);
181        let resp = req.send().await?;
182        let status = resp.status();
183        if status.is_success() {
184            let text = resp.text().await.unwrap_or_default();
185            serde_json::from_str(&text).map_err(|err| {
186                crate::types::error::Error::from_serde_error(
187                    format_serde_error::SerdeError::new(text.to_string(), err),
188                    status,
189                )
190            })
191        } else {
192            let text = resp.text().await.unwrap_or_default();
193            Err(crate::types::error::Error::Server {
194                body: text.to_string(),
195                status,
196            })
197        }
198    }
199
200    #[doc = "Delete a custom object\n\n**Parameters:**\n\n- `custom_object_api_name: &'astr` \
201             (required)\n\n```rust,no_run\nasync fn example_custom_objects_delete() -> \
202             anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    \
203             client.custom_objects().delete(\"some-string\").await?;\n    Ok(())\n}\n```"]
204    #[tracing::instrument]
205    pub async fn delete<'a>(
206        &'a self,
207        custom_object_api_name: &'a str,
208    ) -> Result<(), crate::types::error::Error> {
209        let mut req = self.client.client.request(
210            http::Method::DELETE,
211            format!(
212                "{}/{}",
213                self.client.base_url,
214                "custom-objects/{custom_object_api_name}"
215                    .replace("{custom_object_api_name}", custom_object_api_name)
216            ),
217        );
218        req = req.bearer_auth(&self.client.token);
219        let resp = req.send().await?;
220        let status = resp.status();
221        if status.is_success() {
222            Ok(())
223        } else {
224            let text = resp.text().await.unwrap_or_default();
225            Err(crate::types::error::Error::Server {
226                body: text.to_string(),
227                status,
228            })
229        }
230    }
231
232    #[doc = "Update a custom object\n\nUpdated a specific custom object\n\n**Parameters:**\n\n- \
233             `custom_object_api_name: &'astr` (required)\n\n```rust,no_run\nasync fn \
234             example_custom_objects_update() -> anyhow::Result<()> {\n    let client = \
235             rippling_api::Client::new_from_env();\n    let result: \
236             rippling_api::types::CustomObject = client\n        .custom_objects()\n        \
237             .update(\n            \"some-string\",\n            \
238             &rippling_api::types::UpdateCustomObjectsRequestBody {\n                name: \
239             Some(\"some-string\".to_string()),\n                description: \
240             Some(\"some-string\".to_string()),\n                category: \
241             Some(\"some-string\".to_string()),\n                plural_label: \
242             Some(\"some-string\".to_string()),\n                owner_role: \
243             Some(\"some-string\".to_string()),\n            },\n        )\n        .await?;\n    \
244             println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
245    #[tracing::instrument]
246    pub async fn update<'a>(
247        &'a self,
248        custom_object_api_name: &'a str,
249        body: &crate::types::UpdateCustomObjectsRequestBody,
250    ) -> Result<crate::types::CustomObject, crate::types::error::Error> {
251        let mut req = self.client.client.request(
252            http::Method::PATCH,
253            format!(
254                "{}/{}",
255                self.client.base_url,
256                "custom-objects/{custom_object_api_name}"
257                    .replace("{custom_object_api_name}", custom_object_api_name)
258            ),
259        );
260        req = req.bearer_auth(&self.client.token);
261        req = req.json(body);
262        let resp = req.send().await?;
263        let status = resp.status();
264        if status.is_success() {
265            let text = resp.text().await.unwrap_or_default();
266            serde_json::from_str(&text).map_err(|err| {
267                crate::types::error::Error::from_serde_error(
268                    format_serde_error::SerdeError::new(text.to_string(), err),
269                    status,
270                )
271            })
272        } else {
273            let text = resp.text().await.unwrap_or_default();
274            Err(crate::types::error::Error::Server {
275                body: text.to_string(),
276                status,
277            })
278        }
279    }
280}