/
subgraph.rs
55 lines (47 loc) 路 1.75 KB
/
subgraph.rs
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
use crate::{plugin_utils, Request, Response, SubgraphRequest, SubgraphResponse};
use futures::future;
use std::{collections::HashMap, sync::Arc, task::Poll};
use tower::{BoxError, Service};
type MockResponses = HashMap<Request, Response>;
#[derive(Clone, Default)]
pub struct MockSubgraph {
// using an arc to improve efficiency when service is cloned
mocks: Arc<MockResponses>,
}
impl MockSubgraph {
pub fn new(mocks: MockResponses) -> Self {
Self {
mocks: Arc::new(mocks),
}
}
}
impl Service<SubgraphRequest> for MockSubgraph {
type Response = SubgraphResponse;
type Error = BoxError;
type Future = future::Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: SubgraphRequest) -> Self::Future {
let builder = plugin_utils::SubgraphResponse::builder().context(req.context);
let response = if let Some(response) = self.mocks.get(req.http_request.body()) {
builder.data(response.data.clone()).build().into()
} else {
tracing::error!(
"could not find mock for query: {}",
serde_json::to_string(req.http_request.body())
.expect("could not serialise request")
);
builder
.errors(vec![crate::Error {
message: "couldn't find mock for query".to_string(),
locations: Default::default(),
path: Default::default(),
extensions: Default::default(),
}])
.build()
.into()
};
future::ok(response)
}
}