Skip to main content

rippling_api/
companies.rs

1use anyhow::Result;
2
3use crate::Client;
4#[derive(Clone, Debug)]
5pub struct Companies {
6    pub client: Client,
7}
8
9impl Companies {
10    #[doc(hidden)]
11    pub fn new(client: Client) -> Self {
12        Self { client }
13    }
14
15    #[doc = "List companies\n\nA List of companies\n- Requires: `API Tier 1`\n- Expandable fields: - Sortable fields: `id`, `created_at`, `updated_at`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n- `expand: Option<String>`\n- `order_by: Option<String>`\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_companies_list_stream() -> anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let mut companies = client.companies();\n    let mut stream = companies.list_stream(\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\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```"]
16    #[tracing::instrument]
17    pub async fn list<'a>(
18        &'a self,
19        cursor: Option<String>,
20        expand: Option<String>,
21        order_by: Option<String>,
22    ) -> Result<crate::types::ListCompaniesResponse, crate::types::error::Error> {
23        let mut req = self.client.client.request(
24            http::Method::GET,
25            format!("{}/{}", self.client.base_url, "companies"),
26        );
27        req = req.bearer_auth(&self.client.token);
28        let mut query_params = vec![];
29        if let Some(p) = cursor {
30            query_params.push(("cursor", p));
31        }
32
33        if let Some(p) = expand {
34            query_params.push(("expand", p));
35        }
36
37        if let Some(p) = order_by {
38            query_params.push(("order_by", p));
39        }
40
41        req = req.query(&query_params);
42        let resp = req.send().await?;
43        let status = resp.status();
44        if status.is_success() {
45            let text = resp.text().await.unwrap_or_default();
46            serde_json::from_str(&text).map_err(|err| {
47                crate::types::error::Error::from_serde_error(
48                    format_serde_error::SerdeError::new(text.to_string(), err),
49                    status,
50                )
51            })
52        } else {
53            let text = resp.text().await.unwrap_or_default();
54            Err(crate::types::error::Error::Server {
55                body: text.to_string(),
56                status,
57            })
58        }
59    }
60
61    #[doc = "List companies\n\nA List of companies\n- Requires: `API Tier 1`\n- Expandable fields: - Sortable fields: `id`, `created_at`, `updated_at`\n\n**Parameters:**\n\n- `cursor: Option<String>`\n- `expand: Option<String>`\n- `order_by: Option<String>`\n\n```rust,no_run\nuse futures_util::TryStreamExt;\nasync fn example_companies_list_stream() -> anyhow::Result<()> {\n    let client = rippling_api::Client::new_from_env();\n    let mut companies = client.companies();\n    let mut stream = companies.list_stream(\n        Some(\"some-string\".to_string()),\n        Some(\"some-string\".to_string()),\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```"]
62    #[tracing::instrument]
63    #[cfg(not(feature = "js"))]
64    pub fn list_stream<'a>(
65        &'a self,
66        expand: Option<String>,
67        order_by: Option<String>,
68    ) -> impl futures::Stream<Item = Result<crate::types::Company, crate::types::error::Error>>
69           + Unpin
70           + '_ {
71        use futures::{StreamExt, TryFutureExt, TryStreamExt};
72
73        use crate::types::paginate::Pagination;
74        self.list(None, expand, order_by)
75            .map_ok(move |result| {
76                let items = futures::stream::iter(result.items().into_iter().map(Ok));
77                let next_pages = futures::stream::try_unfold(
78                    (None, result),
79                    move |(prev_page_token, new_result)| async move {
80                        if new_result.has_more_pages()
81                            && !new_result.items().is_empty()
82                            && prev_page_token != new_result.next_page_token()
83                        {
84                            async {
85                                let mut req = self.client.client.request(
86                                    http::Method::GET,
87                                    format!("{}/{}", self.client.base_url, "companies"),
88                                );
89                                req = req.bearer_auth(&self.client.token);
90                                let mut request = req.build()?;
91                                request = new_result.next_page(request)?;
92                                let resp = self.client.client.execute(request).await?;
93                                let status = resp.status();
94                                if status.is_success() {
95                                    let text = resp.text().await.unwrap_or_default();
96                                    serde_json::from_str(&text).map_err(|err| {
97                                        crate::types::error::Error::from_serde_error(
98                                            format_serde_error::SerdeError::new(
99                                                text.to_string(),
100                                                err,
101                                            ),
102                                            status,
103                                        )
104                                    })
105                                } else {
106                                    let text = resp.text().await.unwrap_or_default();
107                                    Err(crate::types::error::Error::Server {
108                                        body: text.to_string(),
109                                        status,
110                                    })
111                                }
112                            }
113                            .map_ok(|result: crate::types::ListCompaniesResponse| {
114                                Some((
115                                    futures::stream::iter(result.items().into_iter().map(Ok)),
116                                    (new_result.next_page_token(), result),
117                                ))
118                            })
119                            .await
120                        } else {
121                            Ok(None)
122                        }
123                    },
124                )
125                .try_flatten();
126                items.chain(next_pages)
127            })
128            .try_flatten_stream()
129            .boxed()
130    }
131}