Skip to main content

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