rippling_api/
compensations.rs

1use anyhow::Result;
2
3use crate::Client;
4#[derive(Clone, Debug)]
5pub struct Compensations {
6    pub client: Client,
7}
8
9impl Compensations {
10    #[doc(hidden)]
11    pub fn new(client: Client) -> Self {
12        Self { client }
13    }
14
15    #[doc = "List compensations\n\nA List of compensations\n- Requires: `API Tier 2`\n- Expandable \
16             fields: `worker`\n- Sortable fields: `id`, `created_at`, \
17             `updated_at`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n- `expand: \
18             Option<String>`\n- `order_by: Option<String>`\n\n```rust,no_run\nuse \
19             futures_util::TryStreamExt;\nasync fn example_compensations_list_stream() -> \
20             anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let \
21             mut compensations = client.compensations();\n    let mut stream = \
22             compensations.list_stream(\n        Some(\"some-string\".to_string()),\n        \
23             Some(\"some-string\".to_string()),\n    );\n    loop {\n        match \
24             stream.try_next().await {\n            Ok(Some(item)) => {\n                \
25             println!(\"{:?}\", item);\n            }\n            Ok(None) => {\n                \
26             break;\n            }\n            Err(err) => {\n                return \
27             Err(err.into());\n            }\n        }\n    }\n\n    Ok(())\n}\n```"]
28    #[tracing::instrument]
29    pub async fn list<'a>(
30        &'a self,
31        cursor: Option<String>,
32        expand: Option<String>,
33        order_by: Option<String>,
34    ) -> Result<crate::types::ListCompensationsResponse, crate::types::error::Error> {
35        let mut req = self.client.client.request(
36            http::Method::GET,
37            format!("{}/{}", self.client.base_url, "compensations"),
38        );
39        req = req.bearer_auth(&self.client.token);
40        let mut query_params = vec![];
41        if let Some(p) = cursor {
42            query_params.push(("cursor", p));
43        }
44
45        if let Some(p) = expand {
46            query_params.push(("expand", p));
47        }
48
49        if let Some(p) = order_by {
50            query_params.push(("order_by", p));
51        }
52
53        req = req.query(&query_params);
54        let resp = req.send().await?;
55        let status = resp.status();
56        if status.is_success() {
57            let text = resp.text().await.unwrap_or_default();
58            serde_json::from_str(&text).map_err(|err| {
59                crate::types::error::Error::from_serde_error(
60                    format_serde_error::SerdeError::new(text.to_string(), err),
61                    status,
62                )
63            })
64        } else {
65            let text = resp.text().await.unwrap_or_default();
66            Err(crate::types::error::Error::Server {
67                body: text.to_string(),
68                status,
69            })
70        }
71    }
72
73    #[doc = "List compensations\n\nA List of compensations\n- Requires: `API Tier 2`\n- Expandable \
74             fields: `worker`\n- Sortable fields: `id`, `created_at`, \
75             `updated_at`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n- `expand: \
76             Option<String>`\n- `order_by: Option<String>`\n\n```rust,no_run\nuse \
77             futures_util::TryStreamExt;\nasync fn example_compensations_list_stream() -> \
78             anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let \
79             mut compensations = client.compensations();\n    let mut stream = \
80             compensations.list_stream(\n        Some(\"some-string\".to_string()),\n        \
81             Some(\"some-string\".to_string()),\n    );\n    loop {\n        match \
82             stream.try_next().await {\n            Ok(Some(item)) => {\n                \
83             println!(\"{:?}\", item);\n            }\n            Ok(None) => {\n                \
84             break;\n            }\n            Err(err) => {\n                return \
85             Err(err.into());\n            }\n        }\n    }\n\n    Ok(())\n}\n```"]
86    #[tracing::instrument]
87    #[cfg(not(feature = "js"))]
88    pub fn list_stream<'a>(
89        &'a self,
90        expand: Option<String>,
91        order_by: Option<String>,
92    ) -> impl futures::Stream<Item = Result<crate::types::Compensation, crate::types::error::Error>>
93           + Unpin
94           + '_ {
95        use futures::{StreamExt, TryFutureExt, TryStreamExt};
96
97        use crate::types::paginate::Pagination;
98        self.list(None, expand, order_by)
99            .map_ok(move |result| {
100                let items = futures::stream::iter(result.items().into_iter().map(Ok));
101                let next_pages = futures::stream::try_unfold(
102                    (None, result),
103                    move |(prev_page_token, new_result)| async move {
104                        if new_result.has_more_pages()
105                            && !new_result.items().is_empty()
106                            && prev_page_token != new_result.next_page_token()
107                        {
108                            async {
109                                let mut req = self.client.client.request(
110                                    http::Method::GET,
111                                    format!("{}/{}", self.client.base_url, "compensations"),
112                                );
113                                req = req.bearer_auth(&self.client.token);
114                                let mut request = req.build()?;
115                                request = new_result.next_page(request)?;
116                                let resp = self.client.client.execute(request).await?;
117                                let status = resp.status();
118                                if status.is_success() {
119                                    let text = resp.text().await.unwrap_or_default();
120                                    serde_json::from_str(&text).map_err(|err| {
121                                        crate::types::error::Error::from_serde_error(
122                                            format_serde_error::SerdeError::new(
123                                                text.to_string(),
124                                                err,
125                                            ),
126                                            status,
127                                        )
128                                    })
129                                } else {
130                                    let text = resp.text().await.unwrap_or_default();
131                                    Err(crate::types::error::Error::Server {
132                                        body: text.to_string(),
133                                        status,
134                                    })
135                                }
136                            }
137                            .map_ok(|result: crate::types::ListCompensationsResponse| {
138                                Some((
139                                    futures::stream::iter(result.items().into_iter().map(Ok)),
140                                    (new_result.next_page_token(), result),
141                                ))
142                            })
143                            .await
144                        } else {
145                            Ok(None)
146                        }
147                    },
148                )
149                .try_flatten();
150                items.chain(next_pages)
151            })
152            .try_flatten_stream()
153            .boxed()
154    }
155
156    #[doc = "Retrieve a specific compensation\n\nRetrieves the Compensation for the Worker with the ID provided in the URL path.\n\n**Parameters:**\n\n- `expand: Option<String>`\n- `id: &'astr`: ID of the resource to return (required)\n\n```rust,no_run\nasync fn example_compensations_get() -> anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let result: rippling_api::types::GetCompensationsResponse = client\n        .compensations()\n        .get(\n            Some(\"some-string\".to_string()),\n            \"d9797f8d-9ad6-4e08-90d7-2ec17e13471c\",\n        )\n        .await?;\n    println!(\"{:?}\", result);\n    Ok(())\n}\n```"]
157    #[tracing::instrument]
158    pub async fn get<'a>(
159        &'a self,
160        expand: Option<String>,
161        id: &'a str,
162    ) -> Result<crate::types::GetCompensationsResponse, crate::types::error::Error> {
163        let mut req = self.client.client.request(
164            http::Method::GET,
165            format!(
166                "{}/{}",
167                self.client.base_url,
168                "compensations/{id}".replace("{id}", id)
169            ),
170        );
171        req = req.bearer_auth(&self.client.token);
172        let mut query_params = vec![];
173        if let Some(p) = expand {
174            query_params.push(("expand", p));
175        }
176
177        req = req.query(&query_params);
178        let resp = req.send().await?;
179        let status = resp.status();
180        if status.is_success() {
181            let text = resp.text().await.unwrap_or_default();
182            serde_json::from_str(&text).map_err(|err| {
183                crate::types::error::Error::from_serde_error(
184                    format_serde_error::SerdeError::new(text.to_string(), err),
185                    status,
186                )
187            })
188        } else {
189            let text = resp.text().await.unwrap_or_default();
190            Err(crate::types::error::Error::Server {
191                body: text.to_string(),
192                status,
193            })
194        }
195    }
196}