crux_http 0.17.0

HTTP capability for use with crux_core
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use crate::middleware::Middleware;
use crate::{Client, HttpError, Request, ResponseAsync, Result};

use futures_util::future::BoxFuture;
use http_types::{
    Body, Method, Mime, Url,
    convert::DeserializeOwned,
    headers::{HeaderName, ToHeaderValues},
};
use serde::Serialize;

use std::{fmt, marker::PhantomData};

/// Request Builder
///
/// Provides an ergonomic way to chain the creation of a request.
/// This is generally accessed as the return value from `Http::{method}()`.
///
/// # Examples
///
/// ```no_run
/// use crux_http::http::{mime::HTML};
/// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
/// # #[crux_core::macros::effect]
/// # enum Effect { Http(crux_http::HttpRequest) }
/// # type Http = crux_http::Http<Effect, Event>;
/// let cmd = Http::post("https://httpbin.org/post")
///     .body("<html>hi</html>")
///     .header("custom-header", "value")
///     .content_type(HTML)
///     .build()
///     .then_send(Event::ReceiveResponse);
/// ```
#[must_use]
pub struct RequestBuilder<Event, ExpectBody = Vec<u8>> {
    /// Holds the state of the request.
    req: Option<Request>,

    client: Client,

    phantom_event: PhantomData<fn() -> Event>,

    phantom_expect: PhantomData<fn() -> ExpectBody>,
}

impl RequestBuilder<(), Vec<u8>> {
    pub(crate) fn new_for_middleware(method: Method, url: Url, client: Client) -> Self {
        Self {
            req: Some(Request::new(method, url)),
            client,
            phantom_event: PhantomData,
            phantom_expect: PhantomData,
        }
    }
}

impl<Event, ExpectBody> RequestBuilder<Event, ExpectBody>
where
    Event: 'static,
    ExpectBody: 'static,
{
    /// Sets a header on the request.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::get("https://httpbin.org/get")
    ///     .body("<html>hi</html>")
    ///     .header("header-name", "header-value")
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    pub fn header(mut self, key: impl Into<HeaderName>, value: impl ToHeaderValues) -> Self {
        self.req.as_mut().unwrap().insert_header(key, value);
        self
    }

    /// Sets the Content-Type header on the request.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use crux_http::http::mime;
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::get("https://httpbin.org/get")
    ///     .content_type(mime::HTML)
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    ///
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
        self.req
            .as_mut()
            .unwrap()
            .set_content_type(content_type.into());
        self
    }

    /// Sets the body of the request from any type with implements `Into<Body>`, for example, any type with is `AsyncRead`.
    /// # Mime
    ///
    /// The encoding is set to `application/octet-stream`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// use serde_json::json;
    /// use crux_http::http::mime;
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .body(json!({"any": "Into<Body>"}))
    ///     .content_type(mime::HTML)
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    pub fn body(mut self, body: impl Into<Body>) -> Self {
        self.req.as_mut().unwrap().set_body(body);
        self
    }

    /// Pass JSON as the request body.
    ///
    /// # Mime
    ///
    /// The encoding is set to `application/json`.
    ///
    /// # Errors
    ///
    /// This method will return an error if the provided data could not be serialized to JSON.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use serde::{Deserialize, Serialize};
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// #[derive(Deserialize, Serialize)]
    /// struct Ip {
    ///     ip: String
    /// }
    ///
    /// let data = &Ip { ip: "129.0.0.1".into() };
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .body_json(data)
    ///     .expect("could not serialize body")
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn body_json(self, json: &impl Serialize) -> crate::Result<Self> {
        Ok(self.body(Body::from_json(json)?))
    }

    /// Pass a string as the request body.
    ///
    /// # Mime
    ///
    /// The encoding is set to `text/plain; charset=utf-8`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .body_string("hello_world".to_string())
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn body_string(self, string: String) -> Self {
        self.body(Body::from_string(string))
    }

    /// Pass bytes as the request body.
    ///
    /// # Mime
    ///
    /// The encoding is set to `application/octet-stream`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .body_bytes(b"hello_world".to_owned())
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn body_bytes(self, bytes: impl AsRef<[u8]>) -> Self {
        self.body(Body::from(bytes.as_ref()))
    }

    /// Pass form data as the request body. The form data needs to be
    /// serializable to name-value pairs.
    ///
    /// # Mime
    ///
    /// The `content-type` is set to `application/x-www-form-urlencoded`.
    ///
    /// # Errors
    ///
    /// An error will be returned if the provided data cannot be serialized to
    /// form data.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let form_data = HashMap::from([
    ///     ("name", "Alice"),
    ///     ("location", "UK"),
    /// ]);
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .body_form(&form_data)
    ///     .expect("could not serialize body")
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn body_form(self, form: &impl Serialize) -> crate::Result<Self> {
        Ok(self.body(Body::from_form(form)?))
    }

    /// Set the URL querystring.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use serde::{Deserialize, Serialize};
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// #[derive(Serialize, Deserialize)]
    /// struct Index {
    ///     page: u32
    /// }
    ///
    /// let query = Index { page: 2 };
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .query(&query)
    ///     .expect("could not serialize query string")
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    /// # Errors
    /// Returns an error if the query string cannot be serialized.
    pub fn query(mut self, query: &impl Serialize) -> std::result::Result<Self, HttpError> {
        self.req.as_mut().unwrap().set_query(query)?;

        Ok(self)
    }

    /// Push middleware onto a per-request middleware stack.
    ///
    /// **Important**: Setting per-request middleware incurs extra allocations.
    /// Creating a `Client` with middleware is recommended.
    ///
    /// Client middleware is run before per-request middleware.
    ///
    /// See the [middleware] submodule for more information on middleware.
    ///
    /// [middleware]: ../middleware/index.html
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Vec<u8>>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::get("https://httpbin.org/redirect/2")
    ///     .middleware(crux_http::middleware::Redirect::default())
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    pub fn middleware(mut self, middleware: impl Middleware) -> Self {
        self.req.as_mut().unwrap().middleware(middleware);
        self
    }

    /// Return the constructed `Request`.
    /// # Panics
    /// Panics if the `RequestBuilder` has not been initialized.
    #[must_use]
    pub fn build(self) -> Request {
        self.req.unwrap()
    }

    /// Decode a String from the response body prior to dispatching it to the apps `update`
    /// function.
    ///
    /// This has no effect when used with the [async API](RequestBuilder::send_async).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<String>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// let cmd = Http::post("https://httpbin.org/post")
    ///     .expect_string()
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn expect_string(self) -> RequestBuilder<Event, String> {
        RequestBuilder {
            req: self.req,
            client: self.client,
            phantom_event: PhantomData,
            phantom_expect: PhantomData,
        }
    }

    /// Decode a `T` from a JSON response body prior to dispatching it to the apps `update`
    /// function.
    ///
    /// This has no effect when used with the [async API](RequestBuilder::send_async).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use serde::{Deserialize, Serialize};
    /// # enum Event { ReceiveResponse(crux_http::Result<crux_http::Response<Slideshow>>) }
    /// # #[crux_core::macros::effect]
    /// # enum Effect { Http(crux_http::HttpRequest) }
    /// # type Http = crux_http::Http<Effect, Event>;
    /// #[derive(Deserialize)]
    /// struct Response {
    ///     slideshow: Slideshow
    /// }
    ///
    /// #[derive(Deserialize)]
    /// struct Slideshow {
    ///     author: String
    /// }
    ///
    /// let cmd = Http::post("https://httpbin.org/json")
    ///     .expect_json::<Slideshow>()
    ///     .build()
    ///     .then_send(Event::ReceiveResponse);
    /// ```
    pub fn expect_json<T>(self) -> RequestBuilder<Event, T>
    where
        T: DeserializeOwned + 'static,
    {
        RequestBuilder {
            req: self.req,
            client: self.client,
            phantom_event: PhantomData,
            phantom_expect: PhantomData,
        }
    }

    /// Sends the constructed `Request` and returns a future that resolves to [`ResponseAsync`].
    /// but does not consume it or convert the body to an expected format.
    ///
    /// Note that this is equivalent to calling `.into_future()` on the `RequestBuilder`, which
    /// will happen implicitly when calling `.await` on the builder, which does implement
    /// [`IntoFuture`](std::future::IntoFuture). Calling `.await` on the builder is recommended.
    ///
    /// Not all code working with futures (such as the `join` macro) works with `IntoFuture` (yet?), so this
    /// method is provided as a more discoverable `.into_future` alias, and may be deprecated later.
    #[must_use]
    pub fn send_async(self) -> BoxFuture<'static, Result<ResponseAsync>> {
        <Self as std::future::IntoFuture>::into_future(self)
    }
}

impl<T, Eb> std::future::IntoFuture for RequestBuilder<T, Eb> {
    type Output = Result<ResponseAsync>;

    type IntoFuture = BoxFuture<'static, Result<ResponseAsync>>;

    /// Sends the constructed `Request` and returns a future that resolves to the response
    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move { self.client.send(self.req.unwrap()).await })
    }
}

impl<Ev> fmt::Debug for RequestBuilder<Ev> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.req, f)
    }
}