Skip to main content

openstack_sdk_identity/v3/region/
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 region.
19//!
20//! When you create the region, you can optionally specify a region ID. If you
21//! include characters in the region ID that are not allowed in a URI, you must
22//! URL-encode the ID. If you omit an ID, the API assigns an ID to the region.
23//!
24//! The following errors might occur:
25//!
26//! Relationship:
27//! `https://docs.openstack.org/api/openstack-identity/3/rel/regions`
28//!
29use derive_builder::Builder;
30use http::{HeaderMap, HeaderName, HeaderValue};
31
32use openstack_sdk_core::api::rest_endpoint_prelude::*;
33
34use serde::Deserialize;
35use serde::Serialize;
36use serde_json::Value;
37use std::borrow::Cow;
38use std::collections::BTreeMap;
39
40/// A `region` object
41#[derive(Builder, Debug, Deserialize, Clone, Serialize)]
42#[builder(setter(strip_option))]
43pub struct Region<'a> {
44    /// The region description.
45    #[serde(skip_serializing_if = "Option::is_none")]
46    #[builder(default, setter(into))]
47    pub(crate) description: Option<Option<Cow<'a, str>>>,
48
49    /// The ID for the region.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    #[builder(default, setter(into))]
52    pub(crate) id: Option<Option<Cow<'a, str>>>,
53
54    /// To make this region a child of another region, set this parameter to
55    /// the ID of the parent region.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    #[builder(default, setter(into))]
58    pub(crate) parent_region_id: Option<Option<Cow<'a, str>>>,
59
60    #[builder(setter(name = "_properties"), default, private)]
61    #[serde(flatten)]
62    _properties: BTreeMap<Cow<'a, str>, Value>,
63}
64
65impl<'a> RegionBuilder<'a> {
66    pub fn properties<I, K, V>(&mut self, iter: I) -> &mut Self
67    where
68        I: Iterator<Item = (K, V)>,
69        K: Into<Cow<'a, str>>,
70        V: Into<Value>,
71    {
72        self._properties
73            .get_or_insert_with(BTreeMap::new)
74            .extend(iter.map(|(k, v)| (k.into(), v.into())));
75        self
76    }
77}
78
79#[derive(Builder, Debug, Clone)]
80#[builder(setter(strip_option))]
81pub struct Request<'a> {
82    /// A `region` object
83    #[builder(setter(into))]
84    pub(crate) region: Region<'a>,
85
86    #[builder(setter(name = "_headers"), default, private)]
87    _headers: Option<HeaderMap>,
88}
89impl<'a> Request<'a> {
90    /// Create a builder for the endpoint.
91    pub fn builder() -> RequestBuilder<'a> {
92        RequestBuilder::default()
93    }
94}
95
96impl<'a> RequestBuilder<'a> {
97    /// Add a single header to the Region.
98    pub fn header<K, V>(&mut self, header_name: K, header_value: V) -> &mut Self
99    where
100        K: Into<HeaderName>,
101        V: Into<HeaderValue>,
102    {
103        self._headers
104            .get_or_insert(None)
105            .get_or_insert_with(HeaderMap::new)
106            .insert(header_name.into(), header_value.into());
107        self
108    }
109
110    /// Add multiple headers.
111    pub fn headers<I, T>(&mut self, iter: I) -> &mut Self
112    where
113        I: Iterator<Item = T>,
114        T: Into<(Option<HeaderName>, HeaderValue)>,
115    {
116        self._headers
117            .get_or_insert(None)
118            .get_or_insert_with(HeaderMap::new)
119            .extend(iter.map(Into::into));
120        self
121    }
122}
123
124impl RestEndpoint for Request<'_> {
125    fn method(&self) -> http::Method {
126        http::Method::POST
127    }
128
129    fn endpoint(&self) -> Cow<'static, str> {
130        "regions".to_string().into()
131    }
132
133    fn parameters(&self) -> QueryParams<'_> {
134        QueryParams::default()
135    }
136
137    fn body(&self) -> Result<Option<(&'static str, Vec<u8>)>, BodyError> {
138        let mut params = JsonBodyParams::default();
139
140        params.push("region", serde_json::to_value(&self.region)?);
141
142        params.into_body()
143    }
144
145    fn service_type(&self) -> ServiceType {
146        ServiceType::Identity
147    }
148
149    fn response_key(&self) -> Option<Cow<'static, str>> {
150        Some("region".into())
151    }
152
153    /// Returns headers to be set into the request
154    fn request_headers(&self) -> Option<&HeaderMap> {
155        self._headers.as_ref()
156    }
157
158    /// Returns required API version
159    fn api_version(&self) -> Option<ApiVersion> {
160        Some(ApiVersion::new(3, 0))
161    }
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167    use http::{HeaderName, HeaderValue};
168    use httpmock::MockServer;
169    #[cfg(feature = "sync")]
170    use openstack_sdk_core::api::Query;
171    use openstack_sdk_core::test::client::FakeOpenStackClient;
172    use openstack_sdk_core::types::ServiceType;
173    use serde_json::json;
174
175    #[test]
176    fn test_service_type() {
177        assert_eq!(
178            Request::builder()
179                .region(RegionBuilder::default().build().unwrap())
180                .build()
181                .unwrap()
182                .service_type(),
183            ServiceType::Identity
184        );
185    }
186
187    #[test]
188    fn test_response_key() {
189        assert_eq!(
190            Request::builder()
191                .region(RegionBuilder::default().build().unwrap())
192                .build()
193                .unwrap()
194                .response_key()
195                .unwrap(),
196            "region"
197        );
198    }
199
200    #[cfg(feature = "sync")]
201    #[test]
202    fn endpoint() {
203        let server = MockServer::start();
204        let client = FakeOpenStackClient::new(server.base_url());
205        let mock = server.mock(|when, then| {
206            when.method(httpmock::Method::POST)
207                .path("/regions".to_string());
208
209            then.status(200)
210                .header("content-type", "application/json")
211                .json_body(json!({ "region": {} }));
212        });
213
214        let endpoint = Request::builder()
215            .region(RegionBuilder::default().build().unwrap())
216            .build()
217            .unwrap();
218        let _: serde_json::Value = endpoint.query(&client).unwrap();
219        mock.assert();
220    }
221
222    #[cfg(feature = "sync")]
223    #[test]
224    fn endpoint_headers() {
225        let server = MockServer::start();
226        let client = FakeOpenStackClient::new(server.base_url());
227        let mock = server.mock(|when, then| {
228            when.method(httpmock::Method::POST)
229                .path("/regions".to_string())
230                .header("foo", "bar")
231                .header("not_foo", "not_bar");
232            then.status(200)
233                .header("content-type", "application/json")
234                .json_body(json!({ "region": {} }));
235        });
236
237        let endpoint = Request::builder()
238            .region(RegionBuilder::default().build().unwrap())
239            .headers(
240                [(
241                    Some(HeaderName::from_static("foo")),
242                    HeaderValue::from_static("bar"),
243                )]
244                .into_iter(),
245            )
246            .header(
247                HeaderName::from_static("not_foo"),
248                HeaderValue::from_static("not_bar"),
249            )
250            .build()
251            .unwrap();
252        let _: serde_json::Value = endpoint.query(&client).unwrap();
253        mock.assert();
254    }
255}