Skip to main content

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