openstack_sdk/api/load_balancer/v2/flavor/
create.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Creates a flavor.
19//!
20use derive_builder::Builder;
21use http::{HeaderMap, HeaderName, HeaderValue};
22
23use crate::api::rest_endpoint_prelude::*;
24
25use serde::Deserialize;
26use serde::Serialize;
27use std::borrow::Cow;
28
29/// Defines mandatory and optional attributes of a POST request.
30#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
31#[builder(setter(strip_option))]
32pub struct Flavor<'a> {
33    #[serde(skip_serializing_if = "Option::is_none")]
34    #[builder(default, setter(into))]
35    pub(crate) description: Option<Cow<'a, str>>,
36
37    #[serde(skip_serializing_if = "Option::is_none")]
38    #[builder(default, setter(into))]
39    pub(crate) enabled: Option<bool>,
40
41    #[serde()]
42    #[builder(setter(into))]
43    pub(crate) flavor_profile_id: Cow<'a, str>,
44
45    #[serde()]
46    #[builder(setter(into))]
47    pub(crate) name: Cow<'a, str>,
48}
49
50#[derive(Builder, Debug, Clone)]
51#[builder(setter(strip_option))]
52pub struct Request<'a> {
53    /// Defines mandatory and optional attributes of a POST request.
54    #[builder(setter(into))]
55    pub(crate) flavor: Flavor<'a>,
56
57    #[builder(setter(name = "_headers"), default, private)]
58    _headers: Option<HeaderMap>,
59}
60impl<'a> Request<'a> {
61    /// Create a builder for the endpoint.
62    pub fn builder() -> RequestBuilder<'a> {
63        RequestBuilder::default()
64    }
65}
66
67impl<'a> RequestBuilder<'a> {
68    /// Add a single header to the Flavor.
69    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
70    where
71        K: Into<HeaderName>,
72        V: Into<HeaderValue>,
73    {
74        self._headers
75            .get_or_insert(None)
76            .get_or_insert_with(HeaderMap::new)
77            .insert(header_name.into(), header_value.into());
78        self
79    }
80
81    /// Add multiple headers.
82    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
83    where
84        I: Iterator<Item = T>,
85        T: Into<(Option<HeaderName>, HeaderValue)>,
86    {
87        self._headers
88            .get_or_insert(None)
89            .get_or_insert_with(HeaderMap::new)
90            .extend(iter.map(Into::into));
91        self
92    }
93}
94
95impl RestEndpoint for Request<'_> {
96    fn method(&self) -> http::Method {
97        http::Method::POST
98    }
99
100    fn endpoint(&self) -> Cow<'static, str> {
101        "lbaas/flavors".to_string().into()
102    }
103
104    fn parameters(&self) -> QueryParams<'_> {
105        QueryParams::default()
106    }
107
108    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
109        let mut params = JsonBodyParams::default();
110
111        params.push("flavor", serde_json::to_value(&self.flavor)?);
112
113        params.into_body()
114    }
115
116    fn service_type(&self) -> ServiceType {
117        ServiceType::LoadBalancer
118    }
119
120    fn response_key(&self) -> Option<Cow<'static, str>> {
121        Some("flavor".into())
122    }
123
124    /// Returns headers to be set into the request
125    fn request_headers(&self) -> Option<&HeaderMap> {
126        self._headers.as_ref()
127    }
128
129    /// Returns required API version
130    fn api_version(&self) -> Option<ApiVersion> {
131        Some(ApiVersion::new(2, 0))
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    #[cfg(feature = "sync")]
139    use crate::api::Query;
140    use crate::test::client::FakeOpenStackClient;
141    use crate::types::ServiceType;
142    use http::{HeaderName, HeaderValue};
143    use httpmock::MockServer;
144    use serde_json::json;
145
146    #[test]
147    fn test_service_type() {
148        assert_eq!(
149            Request::builder()
150                .flavor(
151                    FlavorBuilder::default()
152                        .flavor_profile_id("foo")
153                        .name("foo")
154                        .build()
155                        .unwrap()
156                )
157                .build()
158                .unwrap()
159                .service_type(),
160            ServiceType::LoadBalancer
161        );
162    }
163
164    #[test]
165    fn test_response_key() {
166        assert_eq!(
167            Request::builder()
168                .flavor(
169                    FlavorBuilder::default()
170                        .flavor_profile_id("foo")
171                        .name("foo")
172                        .build()
173                        .unwrap()
174                )
175                .build()
176                .unwrap()
177                .response_key()
178                .unwrap(),
179            "flavor"
180        );
181    }
182
183    #[cfg(feature = "sync")]
184    #[test]
185    fn endpoint() {
186        let server = MockServer::start();
187        let client = FakeOpenStackClient::new(server.base_url());
188        let mock = server.mock(|when, then| {
189            when.method(httpmock::Method::POST)
190                .path("/lbaas/flavors".to_string());
191
192            then.status(200)
193                .header("content-type", "application/json")
194                .json_body(json!({ "flavor": {} }));
195        });
196
197        let endpoint = Request::builder()
198            .flavor(
199                FlavorBuilder::default()
200                    .flavor_profile_id("foo")
201                    .name("foo")
202                    .build()
203                    .unwrap(),
204            )
205            .build()
206            .unwrap();
207        let _: serde_json::Value = endpoint.query(&client).unwrap();
208        mock.assert();
209    }
210
211    #[cfg(feature = "sync")]
212    #[test]
213    fn endpoint_headers() {
214        let server = MockServer::start();
215        let client = FakeOpenStackClient::new(server.base_url());
216        let mock = server.mock(|when, then| {
217            when.method(httpmock::Method::POST)
218                .path("/lbaas/flavors".to_string())
219                .header("foo", "bar")
220                .header("not_foo", "not_bar");
221            then.status(200)
222                .header("content-type", "application/json")
223                .json_body(json!({ "flavor": {} }));
224        });
225
226        let endpoint = Request::builder()
227            .flavor(
228                FlavorBuilder::default()
229                    .flavor_profile_id("foo")
230                    .name("foo")
231                    .build()
232                    .unwrap(),
233            )
234            .headers(
235                [(
236                    Some(HeaderName::from_static("foo")),
237                    HeaderValue::from_static("bar"),
238                )]
239                .into_iter(),
240            )
241            .header(
242                HeaderName::from_static("not_foo"),
243                HeaderValue::from_static("not_bar"),
244            )
245            .build()
246            .unwrap();
247        let _: serde_json::Value = endpoint.query(&client).unwrap();
248        mock.assert();
249    }
250}