teloxide_core/requests/
json.rs

1use std::future::IntoFuture;
2
3use serde::{de::DeserializeOwned, Serialize};
4
5use crate::{
6    bot::Bot,
7    requests::{HasPayload, Payload, Request, ResponseResult},
8    RequestError,
9};
10
11/// A ready-to-send Telegram request whose payload is sent using [JSON].
12///
13/// [JSON]: https://core.telegram.org/bots/api#making-requests
14#[must_use = "Requests are lazy and do nothing unless sent"]
15#[derive(Clone)]
16pub struct JsonRequest<P> {
17    bot: Bot,
18    payload: P,
19}
20
21impl<P> JsonRequest<P> {
22    pub const fn new(bot: Bot, payload: P) -> Self {
23        Self { bot, payload }
24    }
25}
26
27impl<P> Request for JsonRequest<P>
28where
29    // FIXME(waffle):
30    //   this is required on stable because of
31    //   https://github.com/rust-lang/rust/issues/76882
32    //   when it's resolved or `type_alias_impl_trait` feature
33    //   stabilized, we should remove 'static restriction
34    //
35    // (though critically, currently we have no
36    // non-'static payloads)
37    P: 'static,
38    P: Payload + Serialize,
39    P::Output: DeserializeOwned,
40{
41    type Err = RequestError;
42    type Send = Send<P>;
43    type SendRef = SendRef<P>;
44
45    fn send(self) -> Self::Send {
46        Send::new(self)
47    }
48
49    fn send_ref(&self) -> Self::SendRef {
50        SendRef::new(self)
51    }
52}
53
54impl<P> IntoFuture for JsonRequest<P>
55where
56    P: 'static,
57    P: Payload + Serialize,
58    P::Output: DeserializeOwned,
59{
60    type Output = Result<P::Output, RequestError>;
61    type IntoFuture = <Self as Request>::Send;
62
63    fn into_future(self) -> Self::IntoFuture {
64        self.send()
65    }
66}
67
68impl<P> HasPayload for JsonRequest<P>
69where
70    P: Payload,
71{
72    type Payload = P;
73
74    fn payload_mut(&mut self) -> &mut Self::Payload {
75        &mut self.payload
76    }
77
78    fn payload_ref(&self) -> &Self::Payload {
79        &self.payload
80    }
81}
82
83impl<P: Payload + Serialize> core::ops::Deref for JsonRequest<P> {
84    type Target = P;
85
86    fn deref(&self) -> &Self::Target {
87        self.payload_ref()
88    }
89}
90
91impl<P: Payload + Serialize> core::ops::DerefMut for JsonRequest<P> {
92    fn deref_mut(&mut self) -> &mut Self::Target {
93        self.payload_mut()
94    }
95}
96
97req_future! {
98    def: |it: JsonRequest<U>| {
99        it.bot.execute_json(&it.payload)
100    }
101    pub Send<U> (inner0) -> ResponseResult<U::Output>
102    where
103        U: 'static,
104        U: Payload + Serialize,
105        U::Output: DeserializeOwned,
106}
107
108req_future! {
109    def: |it: &JsonRequest<U>| {
110        it.bot.execute_json(&it.payload)
111    }
112    pub SendRef<U> (inner1) -> ResponseResult<U::Output>
113    where
114        U: 'static,
115        U: Payload + Serialize,
116        U::Output: DeserializeOwned,
117}