Skip to main content

twilight_http/request/
try_into_request.rs

1mod private {
2    use crate::request::{
3        GetCurrentAuthorizationInformation, GetGateway, GetGatewayAuthed, GetUserApplicationInfo,
4        GetVoiceRegions,
5        application::{
6            command::{
7                CreateGlobalCommand, CreateGuildCommand, DeleteGlobalCommand, DeleteGuildCommand,
8                GetCommandPermissions, GetGlobalCommand, GetGlobalCommands, GetGuildCommand,
9                GetGuildCommandPermissions, GetGuildCommands, SetGlobalCommands, SetGuildCommands,
10                UpdateCommandPermissions, UpdateGlobalCommand, UpdateGuildCommand,
11                create_global_command::{
12                    CreateGlobalChatInputCommand, CreateGlobalMessageCommand,
13                    CreateGlobalUserCommand,
14                },
15                create_guild_command::{
16                    CreateGuildChatInputCommand, CreateGuildMessageCommand, CreateGuildUserCommand,
17                },
18            },
19            emoji::{
20                AddApplicationEmoji, DeleteApplicationEmoji, ListApplicationEmojis,
21                UpdateApplicationEmoji,
22            },
23            interaction::{
24                CreateFollowup, CreateResponse, CreateResponseWithResponse, DeleteFollowup,
25                DeleteResponse, GetFollowup, GetResponse, UpdateFollowup, UpdateResponse,
26            },
27            monetization::{
28                ConsumeEntitlement, DeleteTestEntitlement, GetEntitlement, GetSKUSubscription,
29                GetSKUSubscriptions, GetSKUs, create_test_entitlement::CreateTestEntitlement,
30                get_entitlements::GetEntitlements,
31            },
32        },
33        channel::{
34            CreatePin, CreateTypingTrigger, DeleteChannel, DeleteChannelPermission,
35            DeleteChannelPermissionConfigured, DeletePin, FollowNewsChannel, GetChannel,
36            GetChannelMemberPermissions, GetChannelRolePermissions, GetPins, UpdateChannel,
37            UpdateChannelPermission,
38            invite::{CreateInvite, DeleteInvite, GetChannelInvites, GetInvite},
39            message::{
40                CreateMessage, CrosspostMessage, DeleteMessage, DeleteMessages, GetChannelMessages,
41                GetChannelMessagesConfigured, GetMessage, UpdateMessage,
42            },
43            reaction::{
44                CreateReaction, DeleteAllReaction, DeleteAllReactions, DeleteReaction, GetReactions,
45            },
46            stage::{
47                CreateStageInstance, DeleteStageInstance, GetStageInstance, UpdateStageInstance,
48            },
49            thread::{
50                AddThreadMember, CreateThread, CreateThreadFromMessage,
51                GetJoinedPrivateArchivedThreads, GetPrivateArchivedThreads,
52                GetPublicArchivedThreads, GetThreadMember, GetThreadMembers, JoinThread,
53                LeaveThread, RemoveThreadMember, UpdateThread,
54                create_forum_thread::CreateForumThreadMessage,
55            },
56            webhook::{
57                CreateWebhook, DeleteWebhook, DeleteWebhookMessage, ExecuteWebhook,
58                ExecuteWebhookAndWait, GetChannelWebhooks, GetWebhook, GetWebhookMessage,
59                UpdateWebhook, UpdateWebhookMessage, UpdateWebhookWithToken,
60            },
61        },
62        guild::{
63            CreateGuildChannel, CreateGuildPrune, DeleteGuild, GetActiveThreads, GetAuditLog,
64            GetGuild, GetGuildChannels, GetGuildInvites, GetGuildOnboarding, GetGuildPreview,
65            GetGuildPruneCount, GetGuildVanityUrl, GetGuildVoiceRegions, GetGuildWebhooks,
66            GetGuildWelcomeScreen, GetGuildWidget, GetGuildWidgetSettings, UpdateCurrentMember,
67            UpdateGuild, UpdateGuildChannelPositions, UpdateGuildMfa, UpdateGuildWelcomeScreen,
68            UpdateGuildWidgetSettings,
69            auto_moderation::{
70                CreateAutoModerationRule, DeleteAutoModerationRule, GetAutoModerationRule,
71                GetGuildAutoModerationRules, UpdateAutoModerationRule,
72            },
73            ban::{BulkGuildBan, CreateBan, DeleteBan, GetBan, GetBans},
74            emoji::{CreateEmoji, DeleteEmoji, GetEmoji, GetEmojis, UpdateEmoji},
75            integration::{DeleteGuildIntegration, GetGuildIntegrations},
76            member::{
77                AddGuildMember, AddRoleToMember, GetGuildMemberPermissions, GetGuildMembers,
78                GetMember, RemoveMember, RemoveRoleFromMember, SearchGuildMembers,
79                UpdateGuildMember,
80            },
81            role::{
82                CreateRole, DeleteRole, GetGuildRoleMemberCounts, GetGuildRolePermissions,
83                GetGuildRoles, GetRole, UpdateRole, UpdateRolePositions,
84            },
85            sticker::{
86                CreateGuildSticker, DeleteGuildSticker, GetGuildSticker, GetGuildStickers,
87                UpdateGuildSticker,
88            },
89            update_guild_onboarding::UpdateGuildOnboarding,
90            user::{
91                GetCurrentUserVoiceState, GetUserVoiceState, UpdateCurrentUserVoiceState,
92                UpdateUserVoiceState,
93            },
94        },
95        poll::{EndPoll, GetAnswerVoters},
96        scheduled_event::{
97            CreateGuildExternalScheduledEvent, CreateGuildStageInstanceScheduledEvent,
98            CreateGuildVoiceScheduledEvent, DeleteGuildScheduledEvent, GetGuildScheduledEvent,
99            GetGuildScheduledEventUsers, GetGuildScheduledEvents, UpdateGuildScheduledEvent,
100        },
101        sticker::{GetNitroStickerPacks, GetSticker, GetStickerPack},
102        template::{
103            CreateGuildFromTemplate, CreateTemplate, DeleteTemplate, GetTemplate, GetTemplates,
104            SyncTemplate, UpdateTemplate,
105        },
106        update_user_application::UpdateCurrentUserApplication,
107        user::{
108            CreatePrivateChannel, GetCurrentUser, GetCurrentUserConnections,
109            GetCurrentUserGuildMember, GetCurrentUserGuilds, GetUser, LeaveGuild,
110            UpdateCurrentUser,
111        },
112    };
113
114    pub trait Sealed {}
115
116    impl Sealed for AddApplicationEmoji<'_> {}
117    impl Sealed for AddGuildMember<'_> {}
118    impl Sealed for AddRoleToMember<'_> {}
119    impl Sealed for AddThreadMember<'_> {}
120    impl Sealed for BulkGuildBan<'_> {}
121    impl Sealed for ConsumeEntitlement<'_> {}
122    impl Sealed for CreateAutoModerationRule<'_> {}
123    impl Sealed for CreateBan<'_> {}
124    impl Sealed for CreateEmoji<'_> {}
125    impl Sealed for CreateFollowup<'_> {}
126    impl Sealed for CreateForumThreadMessage<'_> {}
127    impl Sealed for CreateGlobalChatInputCommand<'_> {}
128    impl Sealed for CreateGlobalCommand<'_> {}
129    impl Sealed for CreateGlobalMessageCommand<'_> {}
130    impl Sealed for CreateGlobalUserCommand<'_> {}
131    impl Sealed for CreateGuildChannel<'_> {}
132    impl Sealed for CreateGuildChatInputCommand<'_> {}
133    impl Sealed for CreateGuildCommand<'_> {}
134    impl Sealed for CreateGuildExternalScheduledEvent<'_> {}
135    impl Sealed for CreateGuildFromTemplate<'_> {}
136    impl Sealed for CreateGuildMessageCommand<'_> {}
137    impl Sealed for CreateGuildPrune<'_> {}
138    impl Sealed for CreateGuildStageInstanceScheduledEvent<'_> {}
139    impl Sealed for CreateGuildSticker<'_> {}
140    impl Sealed for CreateGuildUserCommand<'_> {}
141    impl Sealed for CreateGuildVoiceScheduledEvent<'_> {}
142    impl Sealed for CreateInvite<'_> {}
143    impl Sealed for CreateMessage<'_> {}
144    impl Sealed for CreatePin<'_> {}
145    impl Sealed for CreatePrivateChannel<'_> {}
146    impl Sealed for CreateReaction<'_> {}
147    impl Sealed for CreateResponse<'_> {}
148    impl Sealed for CreateResponseWithResponse<'_> {}
149    impl Sealed for CreateRole<'_> {}
150    impl Sealed for CreateStageInstance<'_> {}
151    impl Sealed for CreateTemplate<'_> {}
152    impl Sealed for CreateTestEntitlement<'_> {}
153    impl Sealed for CreateThread<'_> {}
154    impl Sealed for CreateThreadFromMessage<'_> {}
155    impl Sealed for CreateTypingTrigger<'_> {}
156    impl Sealed for CreateWebhook<'_> {}
157    impl Sealed for CrosspostMessage<'_> {}
158    impl Sealed for DeleteAllReaction<'_> {}
159    impl Sealed for DeleteAllReactions<'_> {}
160    impl Sealed for DeleteAutoModerationRule<'_> {}
161    impl Sealed for DeleteBan<'_> {}
162    impl Sealed for DeleteChannel<'_> {}
163    impl Sealed for DeleteChannelPermission<'_> {}
164    impl Sealed for DeleteChannelPermissionConfigured<'_> {}
165    impl Sealed for DeleteEmoji<'_> {}
166    impl Sealed for DeleteFollowup<'_> {}
167    impl Sealed for DeleteGlobalCommand<'_> {}
168    impl Sealed for DeleteGuild<'_> {}
169    impl Sealed for DeleteGuildCommand<'_> {}
170    impl Sealed for DeleteGuildIntegration<'_> {}
171    impl Sealed for DeleteGuildScheduledEvent<'_> {}
172    impl Sealed for DeleteGuildSticker<'_> {}
173    impl Sealed for DeleteInvite<'_> {}
174    impl Sealed for DeleteMessage<'_> {}
175    impl Sealed for DeleteMessages<'_> {}
176    impl Sealed for DeletePin<'_> {}
177    impl Sealed for DeleteReaction<'_> {}
178    impl Sealed for DeleteResponse<'_> {}
179    impl Sealed for DeleteRole<'_> {}
180    impl Sealed for DeleteStageInstance<'_> {}
181    impl Sealed for DeleteTemplate<'_> {}
182    impl Sealed for DeleteWebhook<'_> {}
183    impl Sealed for DeleteWebhookMessage<'_> {}
184    impl Sealed for DeleteTestEntitlement<'_> {}
185    impl Sealed for DeleteApplicationEmoji<'_> {}
186    impl Sealed for UpdateApplicationEmoji<'_> {}
187    impl Sealed for EndPoll<'_> {}
188    impl Sealed for ExecuteWebhook<'_> {}
189    impl Sealed for ExecuteWebhookAndWait<'_> {}
190    impl Sealed for FollowNewsChannel<'_> {}
191    impl Sealed for GetActiveThreads<'_> {}
192    impl Sealed for ListApplicationEmojis<'_> {}
193    impl Sealed for GetAnswerVoters<'_> {}
194    impl Sealed for GetAuditLog<'_> {}
195    impl Sealed for GetAutoModerationRule<'_> {}
196    impl Sealed for GetBan<'_> {}
197    impl Sealed for GetBans<'_> {}
198    impl Sealed for GetChannel<'_> {}
199    impl Sealed for GetChannelInvites<'_> {}
200    impl Sealed for GetChannelMemberPermissions<'_> {}
201    impl Sealed for GetChannelMessages<'_> {}
202    impl Sealed for GetChannelMessagesConfigured<'_> {}
203    impl Sealed for GetChannelRolePermissions<'_> {}
204    impl Sealed for GetChannelWebhooks<'_> {}
205    impl Sealed for GetCommandPermissions<'_> {}
206    impl Sealed for GetCurrentUser<'_> {}
207    impl Sealed for GetCurrentAuthorizationInformation<'_> {}
208    impl Sealed for GetCurrentUserConnections<'_> {}
209    impl Sealed for GetCurrentUserGuildMember<'_> {}
210    impl Sealed for GetCurrentUserGuilds<'_> {}
211    impl Sealed for GetCurrentUserVoiceState<'_> {}
212    impl Sealed for GetEmoji<'_> {}
213    impl Sealed for GetEmojis<'_> {}
214    impl Sealed for GetEntitlements<'_> {}
215    impl Sealed for GetEntitlement<'_> {}
216    impl Sealed for GetFollowup<'_> {}
217    impl Sealed for GetGateway<'_> {}
218    impl Sealed for GetGatewayAuthed<'_> {}
219    impl Sealed for GetGlobalCommand<'_> {}
220    impl Sealed for GetGlobalCommands<'_> {}
221    impl Sealed for GetGuild<'_> {}
222    impl Sealed for GetGuildAutoModerationRules<'_> {}
223    impl Sealed for GetGuildChannels<'_> {}
224    impl Sealed for GetGuildCommand<'_> {}
225    impl Sealed for GetGuildCommandPermissions<'_> {}
226    impl Sealed for GetGuildCommands<'_> {}
227    impl Sealed for GetGuildIntegrations<'_> {}
228    impl Sealed for GetGuildInvites<'_> {}
229    impl Sealed for GetGuildMemberPermissions<'_> {}
230    impl Sealed for GetGuildMembers<'_> {}
231    impl Sealed for GetGuildOnboarding<'_> {}
232    impl Sealed for GetGuildPreview<'_> {}
233    impl Sealed for GetGuildPruneCount<'_> {}
234    impl Sealed for GetGuildRoleMemberCounts<'_> {}
235    impl Sealed for GetGuildRolePermissions<'_> {}
236    impl Sealed for GetGuildRoles<'_> {}
237    impl Sealed for GetGuildScheduledEvent<'_> {}
238    impl Sealed for GetGuildScheduledEventUsers<'_> {}
239    impl Sealed for GetGuildScheduledEvents<'_> {}
240    impl Sealed for GetGuildSticker<'_> {}
241    impl Sealed for GetGuildStickers<'_> {}
242    impl Sealed for GetGuildVanityUrl<'_> {}
243    impl Sealed for GetGuildVoiceRegions<'_> {}
244    impl Sealed for GetGuildWebhooks<'_> {}
245    impl Sealed for GetGuildWelcomeScreen<'_> {}
246    impl Sealed for GetGuildWidget<'_> {}
247    impl Sealed for GetGuildWidgetSettings<'_> {}
248    impl Sealed for GetInvite<'_> {}
249    impl Sealed for GetJoinedPrivateArchivedThreads<'_> {}
250    impl Sealed for GetMember<'_> {}
251    impl Sealed for GetMessage<'_> {}
252    impl Sealed for GetNitroStickerPacks<'_> {}
253    impl Sealed for GetPins<'_> {}
254    impl Sealed for GetPrivateArchivedThreads<'_> {}
255    impl Sealed for GetPublicArchivedThreads<'_> {}
256    impl Sealed for GetReactions<'_> {}
257    impl Sealed for GetResponse<'_> {}
258    impl Sealed for GetRole<'_> {}
259    impl Sealed for GetSKUs<'_> {}
260    impl Sealed for GetSKUSubscriptions<'_> {}
261    impl Sealed for GetSKUSubscription<'_> {}
262    impl Sealed for GetStageInstance<'_> {}
263    impl Sealed for GetStickerPack<'_> {}
264    impl Sealed for GetSticker<'_> {}
265    impl Sealed for GetTemplate<'_> {}
266    impl Sealed for GetTemplates<'_> {}
267    impl Sealed for GetThreadMember<'_> {}
268    impl Sealed for GetThreadMembers<'_> {}
269    impl Sealed for GetUser<'_> {}
270    impl Sealed for GetUserApplicationInfo<'_> {}
271    impl Sealed for GetUserVoiceState<'_> {}
272    impl Sealed for GetVoiceRegions<'_> {}
273    impl Sealed for GetWebhook<'_> {}
274    impl Sealed for GetWebhookMessage<'_> {}
275    impl Sealed for JoinThread<'_> {}
276    impl Sealed for LeaveGuild<'_> {}
277    impl Sealed for LeaveThread<'_> {}
278    impl Sealed for RemoveMember<'_> {}
279    impl Sealed for RemoveRoleFromMember<'_> {}
280    impl Sealed for RemoveThreadMember<'_> {}
281    impl Sealed for SearchGuildMembers<'_> {}
282    impl Sealed for SetGlobalCommands<'_> {}
283    impl Sealed for SetGuildCommands<'_> {}
284    impl Sealed for SyncTemplate<'_> {}
285    impl Sealed for UpdateAutoModerationRule<'_> {}
286    impl Sealed for UpdateChannel<'_> {}
287    impl Sealed for UpdateChannelPermission<'_> {}
288    impl Sealed for UpdateCommandPermissions<'_> {}
289    impl Sealed for UpdateCurrentMember<'_> {}
290    impl Sealed for UpdateCurrentUser<'_> {}
291    impl Sealed for UpdateCurrentUserVoiceState<'_> {}
292    impl Sealed for UpdateEmoji<'_> {}
293    impl Sealed for UpdateFollowup<'_> {}
294    impl Sealed for UpdateGlobalCommand<'_> {}
295    impl Sealed for UpdateGuild<'_> {}
296    impl Sealed for UpdateGuildChannelPositions<'_> {}
297    impl Sealed for UpdateGuildCommand<'_> {}
298    impl Sealed for UpdateGuildMember<'_> {}
299    impl Sealed for UpdateGuildMfa<'_> {}
300    impl Sealed for UpdateGuildOnboarding<'_> {}
301    impl Sealed for UpdateGuildScheduledEvent<'_> {}
302    impl Sealed for UpdateGuildSticker<'_> {}
303    impl Sealed for UpdateGuildWelcomeScreen<'_> {}
304    impl Sealed for UpdateGuildWidgetSettings<'_> {}
305    impl Sealed for UpdateMessage<'_> {}
306    impl Sealed for UpdateResponse<'_> {}
307    impl Sealed for UpdateRole<'_> {}
308    impl Sealed for UpdateRolePositions<'_> {}
309    impl Sealed for UpdateStageInstance<'_> {}
310    impl Sealed for UpdateTemplate<'_> {}
311    impl Sealed for UpdateThread<'_> {}
312    impl Sealed for UpdateUserVoiceState<'_> {}
313    impl Sealed for UpdateWebhook<'_> {}
314    impl Sealed for UpdateWebhookMessage<'_> {}
315    impl Sealed for UpdateWebhookWithToken<'_> {}
316    impl Sealed for UpdateCurrentUserApplication<'_> {}
317}
318
319use super::base::Request;
320use crate::error::Error;
321
322/// Convert a typed request builder into a raw [`Request`].
323///
324/// Converting a typed request builder into a raw request may be preferable in
325/// order to verify whether a request is valid prior to passing it to
326/// [`Client::request`].
327///
328/// Creating raw requests is useful for unit tests and debugging.
329///
330/// # Examples
331///
332/// Convert a [`CreateMessage`] builder into a [`Request`], inspect its body
333/// and route, and then send the request:
334///
335/// ```no_run
336/// # #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> {
337/// use std::{env, str};
338/// use twilight_http::{client::Client, request::TryIntoRequest};
339/// use twilight_model::{channel::Message, id::Id};
340///
341/// let client = Client::new(env::var("DISCORD_TOKEN")?);
342/// let channel_id = Id::new(1);
343/// let builder = client
344///     .create_message(channel_id)
345///     .content("This is a test message!")
346///     .tts(false);
347///
348/// let request = builder.try_into_request()?;
349///
350/// println!("{:?} {}", request.method(), request.path());
351///
352/// if let Some(body) = request.body() {
353///     println!("{}", str::from_utf8(body)?);
354/// }
355///
356/// // Because a raw request is being performed, the output type must be
357/// // explicit.
358/// let response = client.request::<Message>(request).await?;
359/// # Ok(()) }
360/// ```
361///
362/// [`Client::request`]: crate::client::Client::request
363/// [`CreateMessage`]: super::channel::message::CreateMessage
364pub trait TryIntoRequest: private::Sealed {
365    /// Try to convert a request builder into a raw [`Request`].
366    ///
367    /// # Errors
368    ///
369    /// Not all typed request builder conversions return an error and may
370    /// instead always succeed. Refer to the documentation for each
371    /// implementation for clarification.
372    ///
373    /// Requests may return an error type of [`ErrorType::CreatingHeader`] if
374    /// creating an audit log header value fails.
375    ///
376    /// Requests may return an error type of [`ErrorType::Json`] if serializing
377    /// a request body fails.
378    ///
379    /// [`ErrorType::CreatingHeader`]: crate::error::ErrorType::CreatingHeader
380    /// [`ErrorType::Json`]: crate::error::ErrorType::Json
381    fn try_into_request(self) -> Result<Request, Error>;
382}
383
384#[cfg(test)]
385mod tests {
386    use super::TryIntoRequest;
387    use crate::{client::Client, request::Method};
388    use static_assertions::assert_obj_safe;
389    use std::error::Error;
390    use twilight_model::id::Id;
391
392    assert_obj_safe!(TryIntoRequest);
393
394    #[test]
395    fn conversion() -> Result<(), Box<dyn Error>> {
396        let client = Client::new("token".to_owned());
397        let channel_id = Id::new(1);
398        let request = client
399            .create_message(channel_id)
400            .content("test")
401            .try_into_request()?;
402
403        assert_eq!(Some(br#"{"content":"test"}"#.as_ref()), request.body());
404        assert!(request.form().is_none());
405        assert_eq!(Method::Post, request.method());
406
407        Ok(())
408    }
409}