paperless_api_client/
custom_fields.rs

1use crate::Client;
2use anyhow::Result;
3#[derive(Clone, Debug)]
4pub struct CustomFields {
5    pub client: Client,
6}
7
8impl CustomFields {
9    #[doc(hidden)]
10    pub fn new(client: Client) -> Self {
11        Self { client }
12    }
13
14    #[doc = "Perform a `GET` request to `/api/custom_fields/`.\n\n**Parameters:**\n\n- `id: Option<i64>`\n- `id_in: Option<Vec<i64>>`: Multiple values may be separated by commas.\n- `name_icontains: Option<String>`\n- `name_iendswith: Option<String>`\n- `name_iexact: Option<String>`\n- `name_istartswith: Option<String>`\n- `ordering: Option<String>`: Which field to use when ordering the results.\n- `page: Option<i64>`: A page number within the paginated result set.\n- `page_size: Option<i64>`: Number of results to return per page.\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_custom_fields_list_stream() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let mut custom_fields = client.custom_fields();\n    let mut stream = custom_fields.list_stream(\n        Some(4 as i64),\n        Some(vec![4 as i64]),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(4 as i64),\n    );\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```"]
15    #[tracing::instrument]
16    #[allow(non_snake_case)]
17    pub async fn list<'a>(
18        &'a self,
19        id: Option<i64>,
20        id_in: Option<Vec<i64>>,
21        name_icontains: Option<String>,
22        name_iendswith: Option<String>,
23        name_iexact: Option<String>,
24        name_istartswith: Option<String>,
25        ordering: Option<String>,
26        page: Option<i64>,
27        page_size: Option<i64>,
28    ) -> Result<crate::types::PaginatedCustomFieldList, crate::types::error::Error> {
29        let mut req = self.client.client.request(
30            http::Method::GET,
31            format!("{}/{}", self.client.base_url, "api/custom_fields/"),
32        );
33        req = req.header("Authorization", format!("Token {}", &self.client.token));
34        let mut query_params = vec![];
35        if let Some(p) = id {
36            query_params.push(("id", format!("{p}")));
37        }
38
39        if let Some(p) = id_in {
40            query_params.push(("id__in", itertools::join(p, ",")));
41        }
42
43        if let Some(p) = name_icontains {
44            query_params.push(("name__icontains", p));
45        }
46
47        if let Some(p) = name_iendswith {
48            query_params.push(("name__iendswith", p));
49        }
50
51        if let Some(p) = name_iexact {
52            query_params.push(("name__iexact", p));
53        }
54
55        if let Some(p) = name_istartswith {
56            query_params.push(("name__istartswith", p));
57        }
58
59        if let Some(p) = ordering {
60            query_params.push(("ordering", p));
61        }
62
63        if let Some(p) = page {
64            query_params.push(("page", format!("{p}")));
65        }
66
67        if let Some(p) = page_size {
68            query_params.push(("page_size", format!("{p}")));
69        }
70
71        req = req.query(&query_params);
72        let resp = req.send().await?;
73        let status = resp.status();
74        if status.is_success() {
75            let text = resp.text().await.unwrap_or_default();
76            serde_json::from_str(&text).map_err(|err| {
77                crate::types::error::Error::from_serde_error(
78                    format_serde_error::SerdeError::new(text.to_string(), err),
79                    status,
80                )
81            })
82        } else {
83            let text = resp.text().await.unwrap_or_default();
84            Err(crate::types::error::Error::Server {
85                body: text.to_string(),
86                status,
87            })
88        }
89    }
90
91    #[doc = "Perform a `GET` request to `/api/custom_fields/`.\n\n**Parameters:**\n\n- `id: Option<i64>`\n- `id_in: Option<Vec<i64>>`: Multiple values may be separated by commas.\n- `name_icontains: Option<String>`\n- `name_iendswith: Option<String>`\n- `name_iexact: Option<String>`\n- `name_istartswith: Option<String>`\n- `ordering: Option<String>`: Which field to use when ordering the results.\n- `page: Option<i64>`: A page number within the paginated result set.\n- `page_size: Option<i64>`: Number of results to return per page.\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_custom_fields_list_stream() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let mut custom_fields = client.custom_fields();\n    let mut stream = custom_fields.list_stream(\n        Some(4 as i64),\n        Some(vec![4 as i64]),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\n        Some(4 as i64),\n    );\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```"]
92    #[tracing::instrument]
93    #[cfg(not(feature = "js"))]
94    #[allow(non_snake_case)]
95    pub fn list_stream<'a>(
96        &'a self,
97        id: Option<i64>,
98        id__in: Option<Vec<i64>>,
99        name__icontains: Option<String>,
100        name__iendswith: Option<String>,
101        name__iexact: Option<String>,
102        name__istartswith: Option<String>,
103        ordering: Option<String>,
104        page_size: Option<i64>,
105    ) -> impl futures::Stream<Item = Result<crate::types::CustomField, crate::types::error::Error>>
106           + Unpin
107           + '_ {
108        use crate::types::paginate::Pagination;
109        use futures::{StreamExt, TryFutureExt, TryStreamExt};
110        self.list(
111            id,
112            id__in,
113            name__icontains,
114            name__iendswith,
115            name__iexact,
116            name__istartswith,
117            ordering,
118            None,
119            page_size,
120        )
121        .map_ok(move |result| {
122            let items = futures::stream::iter(result.items().into_iter().map(Ok));
123            let next_pages = futures::stream::try_unfold(
124                (None, result),
125                move |(prev_page_token, new_result)| async move {
126                    if new_result.has_more_pages()
127                        && !new_result.items().is_empty()
128                        && prev_page_token != new_result.next_page_token()
129                    {
130                        async {
131                            let mut req = self.client.client.request(
132                                http::Method::GET,
133                                format!("{}/{}", self.client.base_url, "api/custom_fields/"),
134                            );
135                            req = req
136                                .header("Authorization", format!("Token {}", &self.client.token));
137                            let mut request = req.build()?;
138                            request = new_result.next_page(request)?;
139                            let resp = self.client.client.execute(request).await?;
140                            let status = resp.status();
141                            if status.is_success() {
142                                let text = resp.text().await.unwrap_or_default();
143                                serde_json::from_str(&text).map_err(|err| {
144                                    crate::types::error::Error::from_serde_error(
145                                        format_serde_error::SerdeError::new(text.to_string(), err),
146                                        status,
147                                    )
148                                })
149                            } else {
150                                let text = resp.text().await.unwrap_or_default();
151                                Err(crate::types::error::Error::Server {
152                                    body: text.to_string(),
153                                    status,
154                                })
155                            }
156                        }
157                        .map_ok(|result: crate::types::PaginatedCustomFieldList| {
158                            Some((
159                                futures::stream::iter(result.items().into_iter().map(Ok)),
160                                (new_result.next_page_token(), result),
161                            ))
162                        })
163                        .await
164                    } else {
165                        Ok(None)
166                    }
167                },
168            )
169            .try_flatten();
170            items.chain(next_pages)
171        })
172        .try_flatten_stream()
173        .boxed()
174    }
175
176    #[doc = "Perform a `POST` request to `/api/custom_fields/`.\n\n```rust,no_run\nasync fn example_custom_fields_create() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let result: paperless_api_client::types::CustomField = client\n        .custom_fields()\n        .create(&paperless_api_client::types::CustomFieldRequest {\n            name: \"some-string\".to_string(),\n            data_type: paperless_api_client::types::DataTypeEnum::Float,\n            extra_data: Some(serde_json::Value::String(\"some-string\".to_string())),\n        })\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
177    #[tracing::instrument]
178    #[allow(non_snake_case)]
179    pub async fn create<'a>(
180        &'a self,
181        body: &crate::types::CustomFieldRequest,
182    ) -> Result<crate::types::CustomField, crate::types::error::Error> {
183        let mut req = self.client.client.request(
184            http::Method::POST,
185            format!("{}/{}", self.client.base_url, "api/custom_fields/"),
186        );
187        req = req.header("Authorization", format!("Token {}", &self.client.token));
188        req = req.json(body);
189        let resp = req.send().await?;
190        let status = resp.status();
191        if status.is_success() {
192            let text = resp.text().await.unwrap_or_default();
193            serde_json::from_str(&text).map_err(|err| {
194                crate::types::error::Error::from_serde_error(
195                    format_serde_error::SerdeError::new(text.to_string(), err),
196                    status,
197                )
198            })
199        } else {
200            let text = resp.text().await.unwrap_or_default();
201            Err(crate::types::error::Error::Server {
202                body: text.to_string(),
203                status,
204            })
205        }
206    }
207
208    #[doc = "Perform a `GET` request to `/api/custom_fields/{id}/`.\n\n**Parameters:**\n\n- `id: i64`: A unique integer value identifying this custom field. (required)\n\n```rust,no_run\nasync fn example_custom_fields_retrieve() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let result: paperless_api_client::types::CustomField = client.custom_fields().retrieve(4 as i64).await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
209    #[tracing::instrument]
210    #[allow(non_snake_case)]
211    pub async fn retrieve<'a>(
212        &'a self,
213        id: i64,
214    ) -> Result<crate::types::CustomField, crate::types::error::Error> {
215        let mut req = self.client.client.request(
216            http::Method::GET,
217            format!(
218                "{}/{}",
219                self.client.base_url,
220                "api/custom_fields/{id}/".replace("{id}", &format!("{id}"))
221            ),
222        );
223        req = req.header("Authorization", format!("Token {}", &self.client.token));
224        let resp = req.send().await?;
225        let status = resp.status();
226        if status.is_success() {
227            let text = resp.text().await.unwrap_or_default();
228            serde_json::from_str(&text).map_err(|err| {
229                crate::types::error::Error::from_serde_error(
230                    format_serde_error::SerdeError::new(text.to_string(), err),
231                    status,
232                )
233            })
234        } else {
235            let text = resp.text().await.unwrap_or_default();
236            Err(crate::types::error::Error::Server {
237                body: text.to_string(),
238                status,
239            })
240        }
241    }
242
243    #[doc = "Perform a `PUT` request to `/api/custom_fields/{id}/`.\n\n**Parameters:**\n\n- `id: i64`: A unique integer value identifying this custom field. (required)\n\n```rust,no_run\nasync fn example_custom_fields_update() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let result: paperless_api_client::types::CustomField = client\n        .custom_fields()\n        .update(\n            4 as i64,\n            &paperless_api_client::types::CustomFieldRequest {\n                name: \"some-string\".to_string(),\n                data_type: paperless_api_client::types::DataTypeEnum::Float,\n                extra_data: Some(serde_json::Value::String(\"some-string\".to_string())),\n            },\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
244    #[tracing::instrument]
245    #[allow(non_snake_case)]
246    pub async fn update<'a>(
247        &'a self,
248        id: i64,
249        body: &crate::types::CustomFieldRequest,
250    ) -> Result<crate::types::CustomField, crate::types::error::Error> {
251        let mut req = self.client.client.request(
252            http::Method::PUT,
253            format!(
254                "{}/{}",
255                self.client.base_url,
256                "api/custom_fields/{id}/".replace("{id}", &format!("{id}"))
257            ),
258        );
259        req = req.header("Authorization", format!("Token {}", &self.client.token));
260        req = req.json(body);
261        let resp = req.send().await?;
262        let status = resp.status();
263        if status.is_success() {
264            let text = resp.text().await.unwrap_or_default();
265            serde_json::from_str(&text).map_err(|err| {
266                crate::types::error::Error::from_serde_error(
267                    format_serde_error::SerdeError::new(text.to_string(), err),
268                    status,
269                )
270            })
271        } else {
272            let text = resp.text().await.unwrap_or_default();
273            Err(crate::types::error::Error::Server {
274                body: text.to_string(),
275                status,
276            })
277        }
278    }
279
280    #[doc = "Perform a `DELETE` request to `/api/custom_fields/{id}/`.\n\n**Parameters:**\n\n- `id: i64`: A unique integer value identifying this custom field. (required)\n\n```rust,no_run\nasync fn example_custom_fields_destroy() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    client.custom_fields().destroy(4 as i64).await?;\n    Ok(())\n}\n```"]
281    #[tracing::instrument]
282    #[allow(non_snake_case)]
283    pub async fn destroy<'a>(&'a self, id: i64) -> Result<(), crate::types::error::Error> {
284        let mut req = self.client.client.request(
285            http::Method::DELETE,
286            format!(
287                "{}/{}",
288                self.client.base_url,
289                "api/custom_fields/{id}/".replace("{id}", &format!("{id}"))
290            ),
291        );
292        req = req.header("Authorization", format!("Token {}", &self.client.token));
293        let resp = req.send().await?;
294        let status = resp.status();
295        if status.is_success() {
296            Ok(())
297        } else {
298            let text = resp.text().await.unwrap_or_default();
299            Err(crate::types::error::Error::Server {
300                body: text.to_string(),
301                status,
302            })
303        }
304    }
305
306    #[doc = "Perform a `PATCH` request to `/api/custom_fields/{id}/`.\n\n**Parameters:**\n\n- `id: i64`: A unique integer value identifying this custom field. (required)\n\n```rust,no_run\nasync fn example_custom_fields_partial_update() -> anyhow::Result<()> {\n    let client = paperless_api_client::Client::new_from_env();\n    let result: paperless_api_client::types::CustomField = client\n        .custom_fields()\n        .partial_update(\n            4 as i64,\n            &paperless_api_client::types::PatchedCustomFieldRequest {\n                name: Some(\"some-string\".to_string()),\n                data_type: Some(paperless_api_client::types::DataTypeEnum::Float),\n                extra_data: Some(serde_json::Value::String(\"some-string\".to_string())),\n            },\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
307    #[tracing::instrument]
308    #[allow(non_snake_case)]
309    pub async fn partial_update<'a>(
310        &'a self,
311        id: i64,
312        body: &crate::types::PatchedCustomFieldRequest,
313    ) -> Result<crate::types::CustomField, crate::types::error::Error> {
314        let mut req = self.client.client.request(
315            http::Method::PATCH,
316            format!(
317                "{}/{}",
318                self.client.base_url,
319                "api/custom_fields/{id}/".replace("{id}", &format!("{id}"))
320            ),
321        );
322        req = req.header("Authorization", format!("Token {}", &self.client.token));
323        req = req.json(body);
324        let resp = req.send().await?;
325        let status = resp.status();
326        if status.is_success() {
327            let text = resp.text().await.unwrap_or_default();
328            serde_json::from_str(&text).map_err(|err| {
329                crate::types::error::Error::from_serde_error(
330                    format_serde_error::SerdeError::new(text.to_string(), err),
331                    status,
332                )
333            })
334        } else {
335            let text = resp.text().await.unwrap_or_default();
336            Err(crate::types::error::Error::Server {
337                body: text.to_string(),
338                status,
339            })
340        }
341    }
342}