Skip to main content

reqwest_streams/
csv_body.rs

1//! Streaming a CSV request body.
2
3use crate::stream_body::{ReqwestStreamBody, StreamBodyRequest};
4use futures::Stream;
5use http_streams_core::CsvStreamFormat;
6use serde::Serialize;
7
8/// Extension trait for [`reqwest::RequestBuilder`] that streams a CSV request body.
9///
10/// See [`ReqwestStreamBody`] for the HTTP caveats that apply to every streamed request body.
11pub trait CsvStreamRequest {
12    /// Streams `stream` as CSV, setting `Content-Type: text/csv`.
13    ///
14    /// `with_csv_header` writes a header row from the field names before the first record.
15    fn csv_stream_body<S, T>(
16        self,
17        stream: S,
18        with_csv_header: bool,
19        delimiter: u8,
20    ) -> reqwest::RequestBuilder
21    where
22        T: Serialize + Send + 'static,
23        S: Stream<Item = T> + Send + 'static;
24
25    /// Streams a fallible `stream` as CSV.
26    fn try_csv_stream_body<S, T, E>(
27        self,
28        stream: S,
29        with_csv_header: bool,
30        delimiter: u8,
31    ) -> reqwest::RequestBuilder
32    where
33        T: Serialize + Send + 'static,
34        S: Stream<Item = Result<T, E>> + Send + 'static,
35        E: Into<Box<dyn std::error::Error + Send + Sync>> + Send + 'static;
36}
37
38impl CsvStreamRequest for reqwest::RequestBuilder {
39    fn csv_stream_body<S, T>(
40        self,
41        stream: S,
42        with_csv_header: bool,
43        delimiter: u8,
44    ) -> reqwest::RequestBuilder
45    where
46        T: Serialize + Send + 'static,
47        S: Stream<Item = T> + Send + 'static,
48    {
49        self.stream_body(ReqwestStreamBody::new(
50            CsvStreamFormat::new(with_csv_header, delimiter),
51            stream,
52        ))
53    }
54
55    fn try_csv_stream_body<S, T, E>(
56        self,
57        stream: S,
58        with_csv_header: bool,
59        delimiter: u8,
60    ) -> reqwest::RequestBuilder
61    where
62        T: Serialize + Send + 'static,
63        S: Stream<Item = Result<T, E>> + Send + 'static,
64        E: Into<Box<dyn std::error::Error + Send + Sync>> + Send + 'static,
65    {
66        self.stream_body(ReqwestStreamBody::try_new(
67            CsvStreamFormat::new(with_csv_header, delimiter),
68            stream,
69        ))
70    }
71}