twilight_http/request/template/
create_guild_from_template.rs1#[cfg(not(target_os = "wasi"))]
2use crate::response::{Response, ResponseFuture};
3use crate::{
4 client::Client,
5 error::Error,
6 request::{Request, TryIntoRequest},
7 routing::Route,
8};
9use serde::Serialize;
10use std::future::IntoFuture;
11use twilight_model::guild::Guild;
12use twilight_validate::request::{ValidationError, guild_name as validate_guild_name};
13
14#[derive(Serialize)]
15struct CreateGuildFromTemplateFields<'a> {
16 name: &'a str,
17 #[serde(skip_serializing_if = "Option::is_none")]
18 icon: Option<&'a str>,
19}
20
21#[must_use = "requests must be configured and executed"]
32pub struct CreateGuildFromTemplate<'a> {
33 fields: Result<CreateGuildFromTemplateFields<'a>, ValidationError>,
34 http: &'a Client,
35 template_code: &'a str,
36}
37
38impl<'a> CreateGuildFromTemplate<'a> {
39 pub(crate) fn new(http: &'a Client, template_code: &'a str, name: &'a str) -> Self {
40 let fields = Ok(CreateGuildFromTemplateFields { name, icon: None }).and_then(|fields| {
41 validate_guild_name(name)?;
42
43 Ok(fields)
44 });
45
46 Self {
47 fields,
48 http,
49 template_code,
50 }
51 }
52
53 pub const fn icon(mut self, icon: &'a str) -> Self {
61 if let Ok(fields) = self.fields.as_mut() {
62 fields.icon = Some(icon);
63 }
64
65 self
66 }
67}
68
69#[cfg(not(target_os = "wasi"))]
70impl IntoFuture for CreateGuildFromTemplate<'_> {
71 type Output = Result<Response<Guild>, Error>;
72
73 type IntoFuture = ResponseFuture<Guild>;
74
75 fn into_future(self) -> Self::IntoFuture {
76 let http = self.http;
77
78 match self.try_into_request() {
79 Ok(request) => http.request(request),
80 Err(source) => ResponseFuture::error(source),
81 }
82 }
83}
84
85impl TryIntoRequest for CreateGuildFromTemplate<'_> {
86 fn try_into_request(self) -> Result<Request, Error> {
87 let fields = self.fields.map_err(Error::validation)?;
88
89 Request::builder(&Route::CreateGuildFromTemplate {
90 template_code: self.template_code,
91 })
92 .json(&fields)
93 .build()
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100 use std::error::Error;
101
102 #[test]
103 fn test_create_guild_from_template() -> Result<(), Box<dyn Error>> {
104 let client = Client::new("token".into());
105
106 {
107 let expected = r#"{"name":"New Guild"}"#;
108 let actual =
109 CreateGuildFromTemplate::new(&client, "code", "New Guild").try_into_request()?;
110
111 assert_eq!(Some(expected.as_bytes()), actual.body());
112 }
113
114 {
115 let expected = r#"{"name":"New Guild","icon":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI"}"#;
116 let actual = CreateGuildFromTemplate::new(&client, "code", "New Guild")
117 .icon("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI")
118 .try_into_request()?;
119
120 assert_eq!(Some(expected.as_bytes()), actual.body());
121 }
122 Ok(())
123 }
124}