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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
mod graphiql;

use crate::{Request, Response, Error, Data, Body};
use crate::header::{self, RequestHeader, Method, StatusCode, Mime};
use crate::routes::Route;
use crate::util::PinnedFuture;
use crate::error::{ClientErrorKind};

use juniper::{
	RootNode, GraphQLType, GraphQLTypeAsync, GraphQLSubscriptionType,
	ScalarValue
};
use juniper::http::{GraphQLRequest, GraphQLBatchRequest};


#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GraphiQl {
	uri: &'static str,
	graphql_uri: &'static str
}

impl GraphiQl {
	pub const fn new(uri: &'static str, graphql_uri: &'static str) -> Self {
		Self { uri, graphql_uri }
	}
}

impl Route for GraphiQl {
	fn check(&self, header: &RequestHeader) -> bool {
		header.method() == &Method::GET &&
		header.uri().path().starts_with(self.uri)
	}

	fn validate_data(&self, _data: &Data) {}

	fn call<'a>(
		&'a self,
		_req: &'a mut Request,
		_: &'a Data
	) -> PinnedFuture<'a, crate::Result<Response>> {
		PinnedFuture::new(async move {
			Ok(Response::html(
				graphiql::graphiql_source(self.graphql_uri)
			))
		})
	}
}

/// This only supports POST requests
pub struct GraphQl<Ctx, Q, M, Sub, S>
where
	Q: GraphQLType<S, Context=Ctx>,
	M: GraphQLType<S, Context=Ctx>,
	Sub: GraphQLType<S, Context=Ctx>,
	S: ScalarValue
{
	uri: &'static str,
	root_node: RootNode<'static, Q, M, Sub, S>,
	context: Ctx
}

impl<Ctx, Q, M, Sub, S> GraphQl<Ctx, Q, M, Sub, S>
where
	Q: GraphQLType<S, Context=Ctx>,
	M: GraphQLType<S, Context=Ctx>,
	Sub: GraphQLType<S, Context=Ctx>,
	S: ScalarValue
{
	pub fn new(
		uri: &'static str,
		root_node: RootNode<'static, Q, M, Sub, S>,
		context: Ctx
	) -> Self {
		Self { uri, root_node, context }
	}
}

impl<Ctx, Q, M, Sub, S> Route for GraphQl<Ctx, Q, M, Sub, S>
where
	Q: GraphQLTypeAsync<S, Context=Ctx> + Send,
	Q::TypeInfo: Send + Sync,
	M: GraphQLTypeAsync<S, Context=Ctx> + Send,
	M::TypeInfo: Send + Sync,
	Sub: GraphQLSubscriptionType<S, Context=Ctx> + Send,
	Sub::TypeInfo: Send + Sync,
	Ctx: Send + Sync,
	S: ScalarValue + Send + Sync
{
	fn check(&self, header: &RequestHeader) -> bool {
		header.method() == &Method::POST &&
		header.uri().path().starts_with(self.uri)
	}

	fn validate_data(&self, _data: &Data) {}

	fn call<'a>(
		&'a self,
		req: &'a mut Request,
		_: &'a Data
	) -> PinnedFuture<'a, crate::Result<Response>> {
		PinnedFuture::new(async move {
			// get content-type of request
			let content_type = req.header().value(header::CONTENT_TYPE)
				.unwrap_or("");

			let req: GraphQLBatchRequest<S> = match content_type {
				"application/json" => {
					// read json
					req.deserialize().await?
				},
				"application/graphql" => {
					let body = req.body.take().into_string().await
						.map_err(Error::from_client_io)?;

					GraphQLBatchRequest::Single(
						GraphQLRequest::new(body, None, None)
					)
				},
				_ => return Err(ClientErrorKind::BadRequest.into())
			};

			let res = req.execute(&self.root_node, &self.context).await;

			let mut resp = Response::builder()
				.content_type(Mime::JSON);

			if !res.is_ok() {
				resp = resp.status_code(StatusCode::BAD_REQUEST);
			}

			Ok(resp.body(Body::serialize(&res).unwrap()).build())
		})
	}
}