datadog_api_client/datadogV2/api/
api_case_management_attribute.rs

1// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
2// This product includes software developed at Datadog (https://www.datadoghq.com/).
3// Copyright 2019-Present Datadog, Inc.
4use crate::datadog;
5use flate2::{
6    write::{GzEncoder, ZlibEncoder},
7    Compression,
8};
9use reqwest::header::{HeaderMap, HeaderValue};
10use serde::{Deserialize, Serialize};
11use std::io::Write;
12
13/// CreateCustomAttributeConfigError is a struct for typed errors of method [`CaseManagementAttributeAPI::create_custom_attribute_config`]
14#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(untagged)]
16pub enum CreateCustomAttributeConfigError {
17    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
18    UnknownValue(serde_json::Value),
19}
20
21/// DeleteCustomAttributeConfigError is a struct for typed errors of method [`CaseManagementAttributeAPI::delete_custom_attribute_config`]
22#[derive(Debug, Clone, Serialize, Deserialize)]
23#[serde(untagged)]
24pub enum DeleteCustomAttributeConfigError {
25    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
26    UnknownValue(serde_json::Value),
27}
28
29/// GetAllCustomAttributeConfigsByCaseTypeError is a struct for typed errors of method [`CaseManagementAttributeAPI::get_all_custom_attribute_configs_by_case_type`]
30#[derive(Debug, Clone, Serialize, Deserialize)]
31#[serde(untagged)]
32pub enum GetAllCustomAttributeConfigsByCaseTypeError {
33    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
34    UnknownValue(serde_json::Value),
35}
36
37/// GetAllCustomAttributesError is a struct for typed errors of method [`CaseManagementAttributeAPI::get_all_custom_attributes`]
38#[derive(Debug, Clone, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum GetAllCustomAttributesError {
41    APIErrorResponse(crate::datadogV2::model::APIErrorResponse),
42    UnknownValue(serde_json::Value),
43}
44
45/// View and configure custom attributes within Case Management. See the [Case Management page](<https://docs.datadoghq.com/service_management/case_management/>) for more information.
46#[derive(Debug, Clone)]
47pub struct CaseManagementAttributeAPI {
48    config: datadog::Configuration,
49    client: reqwest_middleware::ClientWithMiddleware,
50}
51
52impl Default for CaseManagementAttributeAPI {
53    fn default() -> Self {
54        Self::with_config(datadog::Configuration::default())
55    }
56}
57
58impl CaseManagementAttributeAPI {
59    pub fn new() -> Self {
60        Self::default()
61    }
62    pub fn with_config(config: datadog::Configuration) -> Self {
63        let mut reqwest_client_builder = reqwest::Client::builder();
64
65        if let Some(proxy_url) = &config.proxy_url {
66            let proxy = reqwest::Proxy::all(proxy_url).expect("Failed to parse proxy URL");
67            reqwest_client_builder = reqwest_client_builder.proxy(proxy);
68        }
69
70        let mut middleware_client_builder =
71            reqwest_middleware::ClientBuilder::new(reqwest_client_builder.build().unwrap());
72
73        if config.enable_retry {
74            struct RetryableStatus;
75            impl reqwest_retry::RetryableStrategy for RetryableStatus {
76                fn handle(
77                    &self,
78                    res: &Result<reqwest::Response, reqwest_middleware::Error>,
79                ) -> Option<reqwest_retry::Retryable> {
80                    match res {
81                        Ok(success) => reqwest_retry::default_on_request_success(success),
82                        Err(_) => None,
83                    }
84                }
85            }
86            let backoff_policy = reqwest_retry::policies::ExponentialBackoff::builder()
87                .build_with_max_retries(config.max_retries);
88
89            let retry_middleware =
90                reqwest_retry::RetryTransientMiddleware::new_with_policy_and_strategy(
91                    backoff_policy,
92                    RetryableStatus,
93                );
94
95            middleware_client_builder = middleware_client_builder.with(retry_middleware);
96        }
97
98        let client = middleware_client_builder.build();
99
100        Self { config, client }
101    }
102
103    pub fn with_client_and_config(
104        config: datadog::Configuration,
105        client: reqwest_middleware::ClientWithMiddleware,
106    ) -> Self {
107        Self { config, client }
108    }
109
110    /// Create custom attribute config for a case type
111    pub async fn create_custom_attribute_config(
112        &self,
113        case_type_id: String,
114        body: crate::datadogV2::model::CustomAttributeConfigCreateRequest,
115    ) -> Result<
116        crate::datadogV2::model::CustomAttributeConfigResponse,
117        datadog::Error<CreateCustomAttributeConfigError>,
118    > {
119        match self
120            .create_custom_attribute_config_with_http_info(case_type_id, body)
121            .await
122        {
123            Ok(response_content) => {
124                if let Some(e) = response_content.entity {
125                    Ok(e)
126                } else {
127                    Err(datadog::Error::Serde(serde::de::Error::custom(
128                        "response content was None",
129                    )))
130                }
131            }
132            Err(err) => Err(err),
133        }
134    }
135
136    /// Create custom attribute config for a case type
137    pub async fn create_custom_attribute_config_with_http_info(
138        &self,
139        case_type_id: String,
140        body: crate::datadogV2::model::CustomAttributeConfigCreateRequest,
141    ) -> Result<
142        datadog::ResponseContent<crate::datadogV2::model::CustomAttributeConfigResponse>,
143        datadog::Error<CreateCustomAttributeConfigError>,
144    > {
145        let local_configuration = &self.config;
146        let operation_id = "v2.create_custom_attribute_config";
147
148        let local_client = &self.client;
149
150        let local_uri_str = format!(
151            "{}/api/v2/cases/types/{case_type_id}/custom_attributes",
152            local_configuration.get_operation_host(operation_id),
153            case_type_id = datadog::urlencode(case_type_id)
154        );
155        let mut local_req_builder =
156            local_client.request(reqwest::Method::POST, local_uri_str.as_str());
157
158        // build headers
159        let mut headers = HeaderMap::new();
160        headers.insert("Content-Type", HeaderValue::from_static("application/json"));
161        headers.insert("Accept", HeaderValue::from_static("application/json"));
162
163        // build user agent
164        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
165            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
166            Err(e) => {
167                log::warn!("Failed to parse user agent header: {e}, falling back to default");
168                headers.insert(
169                    reqwest::header::USER_AGENT,
170                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
171                )
172            }
173        };
174
175        // build auth
176        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
177            headers.insert(
178                "DD-API-KEY",
179                HeaderValue::from_str(local_key.key.as_str())
180                    .expect("failed to parse DD-API-KEY header"),
181            );
182        };
183        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
184            headers.insert(
185                "DD-APPLICATION-KEY",
186                HeaderValue::from_str(local_key.key.as_str())
187                    .expect("failed to parse DD-APPLICATION-KEY header"),
188            );
189        };
190
191        // build body parameters
192        let output = Vec::new();
193        let mut ser = serde_json::Serializer::with_formatter(output, datadog::DDFormatter);
194        if body.serialize(&mut ser).is_ok() {
195            if let Some(content_encoding) = headers.get("Content-Encoding") {
196                match content_encoding.to_str().unwrap_or_default() {
197                    "gzip" => {
198                        let mut enc = GzEncoder::new(Vec::new(), Compression::default());
199                        let _ = enc.write_all(ser.into_inner().as_slice());
200                        match enc.finish() {
201                            Ok(buf) => {
202                                local_req_builder = local_req_builder.body(buf);
203                            }
204                            Err(e) => return Err(datadog::Error::Io(e)),
205                        }
206                    }
207                    "deflate" => {
208                        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
209                        let _ = enc.write_all(ser.into_inner().as_slice());
210                        match enc.finish() {
211                            Ok(buf) => {
212                                local_req_builder = local_req_builder.body(buf);
213                            }
214                            Err(e) => return Err(datadog::Error::Io(e)),
215                        }
216                    }
217                    "zstd1" => {
218                        let mut enc = zstd::stream::Encoder::new(Vec::new(), 0).unwrap();
219                        let _ = enc.write_all(ser.into_inner().as_slice());
220                        match enc.finish() {
221                            Ok(buf) => {
222                                local_req_builder = local_req_builder.body(buf);
223                            }
224                            Err(e) => return Err(datadog::Error::Io(e)),
225                        }
226                    }
227                    _ => {
228                        local_req_builder = local_req_builder.body(ser.into_inner());
229                    }
230                }
231            } else {
232                local_req_builder = local_req_builder.body(ser.into_inner());
233            }
234        }
235
236        local_req_builder = local_req_builder.headers(headers);
237        let local_req = local_req_builder.build()?;
238        log::debug!("request content: {:?}", local_req.body());
239        let local_resp = local_client.execute(local_req).await?;
240
241        let local_status = local_resp.status();
242        let local_content = local_resp.text().await?;
243        log::debug!("response content: {}", local_content);
244
245        if !local_status.is_client_error() && !local_status.is_server_error() {
246            match serde_json::from_str::<crate::datadogV2::model::CustomAttributeConfigResponse>(
247                &local_content,
248            ) {
249                Ok(e) => {
250                    return Ok(datadog::ResponseContent {
251                        status: local_status,
252                        content: local_content,
253                        entity: Some(e),
254                    })
255                }
256                Err(e) => return Err(datadog::Error::Serde(e)),
257            };
258        } else {
259            let local_entity: Option<CreateCustomAttributeConfigError> =
260                serde_json::from_str(&local_content).ok();
261            let local_error = datadog::ResponseContent {
262                status: local_status,
263                content: local_content,
264                entity: local_entity,
265            };
266            Err(datadog::Error::ResponseError(local_error))
267        }
268    }
269
270    /// Delete custom attribute config
271    pub async fn delete_custom_attribute_config(
272        &self,
273        case_type_id: String,
274        custom_attribute_id: String,
275    ) -> Result<(), datadog::Error<DeleteCustomAttributeConfigError>> {
276        match self
277            .delete_custom_attribute_config_with_http_info(case_type_id, custom_attribute_id)
278            .await
279        {
280            Ok(_) => Ok(()),
281            Err(err) => Err(err),
282        }
283    }
284
285    /// Delete custom attribute config
286    pub async fn delete_custom_attribute_config_with_http_info(
287        &self,
288        case_type_id: String,
289        custom_attribute_id: String,
290    ) -> Result<datadog::ResponseContent<()>, datadog::Error<DeleteCustomAttributeConfigError>>
291    {
292        let local_configuration = &self.config;
293        let operation_id = "v2.delete_custom_attribute_config";
294
295        let local_client = &self.client;
296
297        let local_uri_str = format!(
298            "{}/api/v2/cases/types/{case_type_id}/custom_attributes/{custom_attribute_id}",
299            local_configuration.get_operation_host(operation_id),
300            case_type_id = datadog::urlencode(case_type_id),
301            custom_attribute_id = datadog::urlencode(custom_attribute_id)
302        );
303        let mut local_req_builder =
304            local_client.request(reqwest::Method::DELETE, local_uri_str.as_str());
305
306        // build headers
307        let mut headers = HeaderMap::new();
308        headers.insert("Accept", HeaderValue::from_static("*/*"));
309
310        // build user agent
311        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
312            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
313            Err(e) => {
314                log::warn!("Failed to parse user agent header: {e}, falling back to default");
315                headers.insert(
316                    reqwest::header::USER_AGENT,
317                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
318                )
319            }
320        };
321
322        // build auth
323        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
324            headers.insert(
325                "DD-API-KEY",
326                HeaderValue::from_str(local_key.key.as_str())
327                    .expect("failed to parse DD-API-KEY header"),
328            );
329        };
330        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
331            headers.insert(
332                "DD-APPLICATION-KEY",
333                HeaderValue::from_str(local_key.key.as_str())
334                    .expect("failed to parse DD-APPLICATION-KEY header"),
335            );
336        };
337
338        local_req_builder = local_req_builder.headers(headers);
339        let local_req = local_req_builder.build()?;
340        log::debug!("request content: {:?}", local_req.body());
341        let local_resp = local_client.execute(local_req).await?;
342
343        let local_status = local_resp.status();
344        let local_content = local_resp.text().await?;
345        log::debug!("response content: {}", local_content);
346
347        if !local_status.is_client_error() && !local_status.is_server_error() {
348            Ok(datadog::ResponseContent {
349                status: local_status,
350                content: local_content,
351                entity: None,
352            })
353        } else {
354            let local_entity: Option<DeleteCustomAttributeConfigError> =
355                serde_json::from_str(&local_content).ok();
356            let local_error = datadog::ResponseContent {
357                status: local_status,
358                content: local_content,
359                entity: local_entity,
360            };
361            Err(datadog::Error::ResponseError(local_error))
362        }
363    }
364
365    /// Get all custom attribute config of case type
366    pub async fn get_all_custom_attribute_configs_by_case_type(
367        &self,
368        case_type_id: String,
369    ) -> Result<
370        crate::datadogV2::model::CustomAttributeConfigsResponse,
371        datadog::Error<GetAllCustomAttributeConfigsByCaseTypeError>,
372    > {
373        match self
374            .get_all_custom_attribute_configs_by_case_type_with_http_info(case_type_id)
375            .await
376        {
377            Ok(response_content) => {
378                if let Some(e) = response_content.entity {
379                    Ok(e)
380                } else {
381                    Err(datadog::Error::Serde(serde::de::Error::custom(
382                        "response content was None",
383                    )))
384                }
385            }
386            Err(err) => Err(err),
387        }
388    }
389
390    /// Get all custom attribute config of case type
391    pub async fn get_all_custom_attribute_configs_by_case_type_with_http_info(
392        &self,
393        case_type_id: String,
394    ) -> Result<
395        datadog::ResponseContent<crate::datadogV2::model::CustomAttributeConfigsResponse>,
396        datadog::Error<GetAllCustomAttributeConfigsByCaseTypeError>,
397    > {
398        let local_configuration = &self.config;
399        let operation_id = "v2.get_all_custom_attribute_configs_by_case_type";
400
401        let local_client = &self.client;
402
403        let local_uri_str = format!(
404            "{}/api/v2/cases/types/{case_type_id}/custom_attributes",
405            local_configuration.get_operation_host(operation_id),
406            case_type_id = datadog::urlencode(case_type_id)
407        );
408        let mut local_req_builder =
409            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
410
411        // build headers
412        let mut headers = HeaderMap::new();
413        headers.insert("Accept", HeaderValue::from_static("application/json"));
414
415        // build user agent
416        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
417            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
418            Err(e) => {
419                log::warn!("Failed to parse user agent header: {e}, falling back to default");
420                headers.insert(
421                    reqwest::header::USER_AGENT,
422                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
423                )
424            }
425        };
426
427        // build auth
428        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
429            headers.insert(
430                "DD-API-KEY",
431                HeaderValue::from_str(local_key.key.as_str())
432                    .expect("failed to parse DD-API-KEY header"),
433            );
434        };
435        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
436            headers.insert(
437                "DD-APPLICATION-KEY",
438                HeaderValue::from_str(local_key.key.as_str())
439                    .expect("failed to parse DD-APPLICATION-KEY header"),
440            );
441        };
442
443        local_req_builder = local_req_builder.headers(headers);
444        let local_req = local_req_builder.build()?;
445        log::debug!("request content: {:?}", local_req.body());
446        let local_resp = local_client.execute(local_req).await?;
447
448        let local_status = local_resp.status();
449        let local_content = local_resp.text().await?;
450        log::debug!("response content: {}", local_content);
451
452        if !local_status.is_client_error() && !local_status.is_server_error() {
453            match serde_json::from_str::<crate::datadogV2::model::CustomAttributeConfigsResponse>(
454                &local_content,
455            ) {
456                Ok(e) => {
457                    return Ok(datadog::ResponseContent {
458                        status: local_status,
459                        content: local_content,
460                        entity: Some(e),
461                    })
462                }
463                Err(e) => return Err(datadog::Error::Serde(e)),
464            };
465        } else {
466            let local_entity: Option<GetAllCustomAttributeConfigsByCaseTypeError> =
467                serde_json::from_str(&local_content).ok();
468            let local_error = datadog::ResponseContent {
469                status: local_status,
470                content: local_content,
471                entity: local_entity,
472            };
473            Err(datadog::Error::ResponseError(local_error))
474        }
475    }
476
477    /// Get all custom attributes
478    pub async fn get_all_custom_attributes(
479        &self,
480    ) -> Result<
481        crate::datadogV2::model::CustomAttributeConfigsResponse,
482        datadog::Error<GetAllCustomAttributesError>,
483    > {
484        match self.get_all_custom_attributes_with_http_info().await {
485            Ok(response_content) => {
486                if let Some(e) = response_content.entity {
487                    Ok(e)
488                } else {
489                    Err(datadog::Error::Serde(serde::de::Error::custom(
490                        "response content was None",
491                    )))
492                }
493            }
494            Err(err) => Err(err),
495        }
496    }
497
498    /// Get all custom attributes
499    pub async fn get_all_custom_attributes_with_http_info(
500        &self,
501    ) -> Result<
502        datadog::ResponseContent<crate::datadogV2::model::CustomAttributeConfigsResponse>,
503        datadog::Error<GetAllCustomAttributesError>,
504    > {
505        let local_configuration = &self.config;
506        let operation_id = "v2.get_all_custom_attributes";
507
508        let local_client = &self.client;
509
510        let local_uri_str = format!(
511            "{}/api/v2/cases/types/custom_attributes",
512            local_configuration.get_operation_host(operation_id)
513        );
514        let mut local_req_builder =
515            local_client.request(reqwest::Method::GET, local_uri_str.as_str());
516
517        // build headers
518        let mut headers = HeaderMap::new();
519        headers.insert("Accept", HeaderValue::from_static("application/json"));
520
521        // build user agent
522        match HeaderValue::from_str(local_configuration.user_agent.as_str()) {
523            Ok(user_agent) => headers.insert(reqwest::header::USER_AGENT, user_agent),
524            Err(e) => {
525                log::warn!("Failed to parse user agent header: {e}, falling back to default");
526                headers.insert(
527                    reqwest::header::USER_AGENT,
528                    HeaderValue::from_static(datadog::DEFAULT_USER_AGENT.as_str()),
529                )
530            }
531        };
532
533        // build auth
534        if let Some(local_key) = local_configuration.auth_keys.get("apiKeyAuth") {
535            headers.insert(
536                "DD-API-KEY",
537                HeaderValue::from_str(local_key.key.as_str())
538                    .expect("failed to parse DD-API-KEY header"),
539            );
540        };
541        if let Some(local_key) = local_configuration.auth_keys.get("appKeyAuth") {
542            headers.insert(
543                "DD-APPLICATION-KEY",
544                HeaderValue::from_str(local_key.key.as_str())
545                    .expect("failed to parse DD-APPLICATION-KEY header"),
546            );
547        };
548
549        local_req_builder = local_req_builder.headers(headers);
550        let local_req = local_req_builder.build()?;
551        log::debug!("request content: {:?}", local_req.body());
552        let local_resp = local_client.execute(local_req).await?;
553
554        let local_status = local_resp.status();
555        let local_content = local_resp.text().await?;
556        log::debug!("response content: {}", local_content);
557
558        if !local_status.is_client_error() && !local_status.is_server_error() {
559            match serde_json::from_str::<crate::datadogV2::model::CustomAttributeConfigsResponse>(
560                &local_content,
561            ) {
562                Ok(e) => {
563                    return Ok(datadog::ResponseContent {
564                        status: local_status,
565                        content: local_content,
566                        entity: Some(e),
567                    })
568                }
569                Err(e) => return Err(datadog::Error::Serde(e)),
570            };
571        } else {
572            let local_entity: Option<GetAllCustomAttributesError> =
573                serde_json::from_str(&local_content).ok();
574            let local_error = datadog::ResponseContent {
575                status: local_status,
576                content: local_content,
577                entity: local_entity,
578            };
579            Err(datadog::Error::ResponseError(local_error))
580        }
581    }
582}