1use std::sync::Arc;
2
3use crate::client::Inner;
4use crate::error::{Error, Result};
5use crate::http::{Request, Response};
6use crate::models::{
7 CacheInfo, CompanyList, CompanyRecord, decode_companies, decode_company_envelope,
8};
9use crate::params::{CompanySearchParams, check_company_id, company_ids_query};
10
11#[derive(Debug, Clone, Copy)]
14pub struct Companies<'a> {
15 pub(crate) inner: &'a Arc<Inner>,
16}
17
18fn cache_info(resp: &Response) -> CacheInfo {
19 CacheInfo {
20 etag: resp.header("etag"),
21 cache_control: resp.header("cache-control"),
22 }
23}
24
25impl Companies<'_> {
26 pub async fn search(&self, params: &CompanySearchParams) -> Result<CompanyList> {
29 let mut req = Request::get("/v3/companies");
30 req.query = params.to_query()?;
31 let resp = self.inner.transport.call(&req).await?;
32 decode_companies(&resp.body)
33 }
34
35 pub async fn get_many(&self, ids: &[i64]) -> Result<CompanyList> {
38 let mut req = Request::get("/v3/companies");
39 req.query.push(("ids", company_ids_query(ids)?));
40 let resp = self.inner.transport.call(&req).await?;
41 decode_companies(&resp.body)
42 }
43
44 pub async fn get(&self, company_id: i64) -> Result<CompanyRecord> {
52 check_company_id(company_id, "company_id")?;
53 let req = Request::get(format!("/v3/companies/{company_id}"));
54 let resp = self.inner.transport.call(&req).await?;
55 if resp.status == 304 {
56 return Err(Error::decode(
57 "the server answered 304 to a request without If-None-Match",
58 None,
59 None,
60 None,
61 ));
62 }
63 let mut record = decode_company_envelope(&resp.body)?;
64 record.set_cache_info(cache_info(&resp));
65 Ok(record)
66 }
67
68 pub async fn get_if_none_match(
74 &self,
75 company_id: i64,
76 etag: &str,
77 ) -> Result<Option<CompanyRecord>> {
78 check_company_id(company_id, "company_id")?;
79 if etag.is_empty() {
80 return Err(Error::validation(
81 "etag must not be empty",
82 Some("if_none_match"),
83 ));
84 }
85 let mut req = Request::get(format!("/v3/companies/{company_id}"));
86 req.if_none_match = Some(etag.to_owned());
87 let resp = self.inner.transport.call(&req).await?;
88 if resp.status == 304 {
89 return Ok(None);
90 }
91 let mut record = decode_company_envelope(&resp.body)?;
92 record.set_cache_info(cache_info(&resp));
93 Ok(Some(record))
94 }
95}