volcengine_rust_sdk/service/ecs/
api_describe_instances_model.rs

1/*
2 * @Author: Jerry.Yang
3 * @Date: 2024-10-29 10:25:09
4 * @LastEditors: Jerry.Yang
5 * @LastEditTime: 2024-12-04 15:02:39
6 * @Description: API describe instances model
7 *
8 * This module defines the `DescribeInstancesReq` and `DescribeInstancesResp` structures
9 * and provides implementations for converting them to/from request and response formats.
10 * The goal is to interface with the ECS (Elastic Compute Service) API for describing ECS instances.
11 *
12 * It includes implementations for two key parts:
13 * 1. `DescribeInstancesReq`: A request struct that can be converted into a `HashMap` or a request body.
14 * 2. `DescribeInstancesResp`: A response struct that processes the HTTP response, converts it into the
15 *    struct, and handles error status codes.
16 */
17use crate::volcengine::error::error;
18use crate::volcengine::request::request::RequestVolcengine;
19use crate::volcengine::request::{request, response};
20use std::collections::HashMap;
21use volcengine_sdk_protobuf::protobuf::ecs_instance;
22
23// Implement the `ApiRequest` trait for the `DescribeInstancesReq` struct.
24//
25// This implementation allows the `DescribeInstancesReq` struct to be used in the process of
26// making requests to the ECS API. Specifically, it provides two methods for converting
27// the request object into a format suitable for an HTTP request:
28// 1. `to_hashmap`: Converts the struct to a `HashMap<String, String>` for sending parameters as part of the query string.
29// 2. `to_body`: Prepares the request body as a vector of bytes (`Vec<u8>`) to be sent in the HTTP request.
30//
31// The `ApiRequest` trait is part of the infrastructure that abstracts the request logic,
32// allowing for different types of requests (e.g., describing instances, managing resources) to
33// be structured and sent to the API consistently. In this case, `DescribeInstancesReq` is used
34// to request information about ECS instances from the service.
35impl request::ApiRequest for ecs_instance::DescribeInstancesReq {
36    /// Converts the `DescribeInstancesReq` struct into a `HashMap<String, String>`.
37    ///
38    /// This function is used for preparing the request parameters in the form of a hashmap,
39    /// which will be used when constructing the HTTP request to the ECS API.
40    ///
41    /// # Returns
42    /// - A `HashMap<String, String>` containing the request parameters in key-value pairs.
43    fn to_hashmap(&self) -> HashMap<String, String> {
44        request::Request::format_request_to_hashmap(self) // Utilize helper function to convert the request to hashmap
45    }
46
47    /// Converts the `DescribeInstancesReq` struct into the request body in `Vec<u8>` format.
48    ///
49    /// This function is responsible for returning an empty vector as the body for the request.
50    /// This might be used for requests that don't require a body or for future expansions if
51    /// the body content is to be added.
52    ///
53    /// # Returns
54    /// - An empty `Vec<u8>`, as this specific request does not contain a body.
55    fn to_body(&self) -> Vec<u8> {
56        let result = Vec::new(); // No body content in this case
57        result
58    }
59}
60
61// Implement the `ApiResponse` trait for the `DescribeInstancesResp` struct.
62//
63// This implementation is crucial for processing the response from the ECS API after a request
64// is made. Specifically, it provides the functionality to:
65// 1. Parse the response body into a `DescribeInstancesResp` struct.
66// 2. Handle any potential error status codes returned by the API and update the response metadata accordingly.
67//
68// The `ApiResponse` trait abstracts the logic for handling API responses. It allows for:
69// - Parsing the JSON response into a structured Rust object (in this case, `DescribeInstancesResp`).
70// - Checking for error conditions, particularly for non-2xx status codes, and updating the response metadata to reflect error details.
71//
72// This ensures that the response is correctly processed and any error handling i
73impl response::ApiResponse for ecs_instance::DescribeInstancesResp {
74    /// Processes the HTTP response and populates the `DescribeInstancesResp` struct.
75    ///
76    /// This function is used for handling the response from the ECS API after a request is sent.
77    /// It processes the HTTP status, parses the JSON response body, and handles error conditions.
78    ///
79    /// # Parameters
80    /// - `http_response`: The HTTP response from the ECS API. This contains the status code and response body.
81    ///
82    /// # Returns
83    /// - `Result<(), error::Error>`: Returns `Ok(())` if the parsing is successful, or an error if there is an issue.
84    async fn to_struct(&mut self, http_response: reqwest::Response) -> Result<(), error::Error> {
85        // Get HTTP status code to check the success of the request
86        let http_status = http_response.status();
87
88        // Parse the JSON response body into the `DescribeInstancesResp` struct
89        let parsed_response: volcengine_sdk_protobuf::protobuf::ecs_instance::DescribeInstancesResp =
90            http_response
91                .json()
92                .await
93                .map_err(error::Error::ErrParseResponse)?; // Map any JSON parsing error to custom error type
94
95        // Update the current struct with the parsed response
96        *self = parsed_response;
97
98        // Check if the response indicates an error (non-2xx status code)
99        if !http_status.is_success() {
100            // If response contains metadata, process it further
101            if let Some(mut response_metadata) = self.response_metadata.take() {
102                // Ensure `error` field exists in `response_metadata`
103                let response_metadata_error = response_metadata.error.get_or_insert_with(
104                    volcengine_sdk_protobuf::protobuf::ecs_instance::ResponseMetadataErr::default,
105                );
106
107                // Set the error code based on HTTP status code (e.g., 404, 500)
108                response_metadata_error.code_n = Some(http_status.as_u16().into());
109
110                // Update the `response_metadata` with the modified error information
111                self.response_metadata = Some(response_metadata);
112            }
113        }
114
115        // Return Ok if processing was successful
116        Ok(())
117    }
118}