jsonrpc_sdk_client/
async.rs

1// Copyright (C) 2019 Boyu Yang
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use futures::{future, Future};
10use reqwest::r#async::{
11    Client as RawClient, ClientBuilder as RawClientBuilder, RequestBuilder as RawRequestBuilder,
12    Response as RawResponse,
13};
14pub use reqwest::{header::HeaderMap, IntoUrl};
15
16use jsonrpc_sdk_prelude::{jsonrpc_core::Response, CommonPart, Error, JsonRpcRequest, Result};
17
18pub struct Client(RawClient);
19pub struct ClientBuilder(RawClientBuilder);
20pub struct RequestBuilder(RawRequestBuilder);
21
22impl Client {
23    pub fn new() -> Self {
24        Client(RawClient::new())
25    }
26
27    pub fn builder() -> ClientBuilder {
28        ClientBuilder(RawClient::builder())
29    }
30
31    pub fn post<U>(&self, url: U) -> RequestBuilder
32    where
33        U: IntoUrl,
34    {
35        RequestBuilder(self.0.post(url))
36    }
37}
38
39impl Default for Client {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl ClientBuilder {
46    pub fn build(self) -> Result<Client> {
47        Ok(Client(self.0.build()?))
48    }
49
50    pub fn tcp_nodelay(self) -> Self {
51        ClientBuilder(self.0.tcp_nodelay())
52    }
53
54    pub fn default_headers(self, headers: HeaderMap) -> Self {
55        ClientBuilder(self.0.default_headers(headers))
56    }
57
58    pub fn gzip(self, enable: bool) -> Self {
59        ClientBuilder(self.0.gzip(enable))
60    }
61
62    pub fn connect_timeout(self, timeout: ::std::time::Duration) -> Self {
63        ClientBuilder(self.0.connect_timeout(timeout))
64    }
65}
66
67impl RequestBuilder {
68    pub fn send<T>(
69        self,
70        content: T,
71        common: CommonPart,
72    ) -> impl Future<Item = T::Output, Error = Error>
73    where
74        T: JsonRpcRequest,
75    {
76        future_error!(content.to_single_request(common)).and_then(|request| {
77            self.0
78                .json(&request)
79                .send()
80                .and_then(RawResponse::error_for_status)
81                .and_then(|mut r| r.json::<Response>())
82                .map_err(std::convert::Into::into)
83                .and_then(T::parse_single_response)
84        })
85    }
86}