alloy_simple_request_transport/
lib.rs1#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2#![doc = include_str!("../README.md")]
3
4use core::task;
5use std::io;
6
7use alloy_json_rpc::{RequestPacket, ResponsePacket};
8use alloy_transport::{TransportError, TransportErrorKind, TransportFut};
9
10use simple_request::{hyper, Request, Client};
11
12use tower::Service;
13
14#[derive(Clone, Debug)]
15pub struct SimpleRequest {
16 client: Client,
17 url: String,
18}
19
20impl SimpleRequest {
21 pub fn new(url: String) -> Self {
22 Self { client: Client::with_connection_pool(), url }
23 }
24}
25
26impl Service<RequestPacket> for SimpleRequest {
27 type Response = ResponsePacket;
28 type Error = TransportError;
29 type Future = TransportFut<'static>;
30
31 #[inline]
32 fn poll_ready(&mut self, _cx: &mut task::Context<'_>) -> task::Poll<Result<(), Self::Error>> {
33 task::Poll::Ready(Ok(()))
34 }
35
36 #[inline]
37 fn call(&mut self, req: RequestPacket) -> Self::Future {
38 let inner = self.clone();
39 Box::pin(async move {
40 let packet = req.serialize().map_err(TransportError::SerError)?;
41 let request = Request::from(
42 hyper::Request::post(&inner.url)
43 .header("Content-Type", "application/json")
44 .body(serde_json::to_vec(&packet).map_err(TransportError::SerError)?.into())
45 .unwrap(),
46 );
47
48 let mut res = inner
49 .client
50 .request(request)
51 .await
52 .map_err(|e| TransportErrorKind::custom(io::Error::other(format!("{e:?}"))))?
53 .body()
54 .await
55 .map_err(|e| TransportErrorKind::custom(io::Error::other(format!("{e:?}"))))?;
56
57 serde_json::from_reader(&mut res).map_err(|e| TransportError::deser_err(e, ""))
58 })
59 }
60}