jsonrpc_sdk_client/
sync.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
9pub use reqwest::{header::HeaderMap, IntoUrl};
10use reqwest::{
11    Client as RawClient, ClientBuilder as RawClientBuilder, RequestBuilder as RawRequestBuilder,
12    Response as RawResponse,
13};
14
15use jsonrpc_sdk_prelude::{jsonrpc_core::Response, CommonPart, JsonRpcRequest, Result};
16
17pub struct Client(RawClient);
18pub struct ClientBuilder(RawClientBuilder);
19pub struct RequestBuilder(RawRequestBuilder);
20
21impl Client {
22    pub fn new() -> Self {
23        Client(RawClient::new())
24    }
25
26    pub fn builder() -> ClientBuilder {
27        ClientBuilder(RawClient::builder())
28    }
29
30    pub fn post<U>(&self, url: U) -> RequestBuilder
31    where
32        U: IntoUrl,
33    {
34        RequestBuilder(self.0.post(url))
35    }
36}
37
38impl Default for Client {
39    fn default() -> Self {
40        Self::new()
41    }
42}
43
44impl ClientBuilder {
45    pub fn build(self) -> Result<Client> {
46        Ok(Client(self.0.build()?))
47    }
48
49    pub fn tcp_nodelay(self) -> Self {
50        ClientBuilder(self.0.tcp_nodelay())
51    }
52
53    pub fn default_headers(self, headers: HeaderMap) -> Self {
54        ClientBuilder(self.0.default_headers(headers))
55    }
56
57    pub fn gzip(self, enable: bool) -> Self {
58        ClientBuilder(self.0.gzip(enable))
59    }
60
61    pub fn connect_timeout(self, timeout: ::std::time::Duration) -> Self {
62        ClientBuilder(self.0.connect_timeout(timeout))
63    }
64}
65
66impl RequestBuilder {
67    pub fn send<T>(self, content: T, common: CommonPart) -> Result<T::Output>
68    where
69        T: JsonRpcRequest,
70    {
71        normal_error!(content.to_single_request(common)).and_then(|request| {
72            self.0
73                .json(&request)
74                .send()
75                .and_then(RawResponse::error_for_status)
76                .and_then(|mut r| r.json::<Response>())
77                .map_err(std::convert::Into::into)
78                .and_then(T::parse_single_response)
79        })
80    }
81}