Skip to main content

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