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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#![warn(missing_docs)]
#![forbid(unsafe_code)]
use core::any::Any;
use std::io::Cursor;
use async_graphql::http::MultipartOptions;
use async_graphql::{ObjectType, ParseRequestError, Schema, SubscriptionType};
use rocket::{
data::{self, Data, FromData, ToByteUnit},
form::FromForm,
http::{ContentType, Header, Status},
response::{self, Responder},
};
use tokio_util::compat::TokioAsyncReadCompatExt;
#[derive(Debug)]
pub struct GraphQLBatchRequest(pub async_graphql::BatchRequest);
impl GraphQLBatchRequest {
pub async fn execute<Query, Mutation, Subscription>(
self,
schema: &Schema<Query, Mutation, Subscription>,
) -> GraphQLResponse
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
GraphQLResponse(schema.execute_batch(self.0).await)
}
}
#[rocket::async_trait]
impl<'r> FromData<'r> for GraphQLBatchRequest {
type Error = ParseRequestError;
async fn from_data(req: &'r rocket::Request<'_>, data: Data<'r>) -> data::Outcome<'r, Self> {
let opts: MultipartOptions = req.rocket().state().copied().unwrap_or_default();
let request = async_graphql::http::receive_batch_body(
req.headers().get_one("Content-Type"),
data.open(
req.limits()
.get("graphql")
.unwrap_or_else(|| 128.kibibytes()),
)
.compat(),
opts,
)
.await;
match request {
Ok(request) => data::Outcome::Success(Self(request)),
Err(e) => data::Outcome::Failure((
match e {
ParseRequestError::PayloadTooLarge => Status::PayloadTooLarge,
_ => Status::BadRequest,
},
e,
)),
}
}
}
#[derive(Debug)]
pub struct GraphQLRequest(pub async_graphql::Request);
impl GraphQLRequest {
pub async fn execute<Query, Mutation, Subscription>(
self,
schema: &Schema<Query, Mutation, Subscription>,
) -> GraphQLResponse
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
GraphQLResponse(schema.execute(self.0).await.into())
}
pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
self.0.data.insert(data);
self
}
}
impl From<GraphQLQuery> for GraphQLRequest {
fn from(query: GraphQLQuery) -> Self {
let mut request = async_graphql::Request::new(query.query);
if let Some(operation_name) = query.operation_name {
request = request.operation_name(operation_name);
}
if let Some(variables) = query.variables {
let value = serde_json::from_str(&variables).unwrap_or_default();
let variables = async_graphql::Variables::from_json(value);
request = request.variables(variables);
}
GraphQLRequest(request)
}
}
#[derive(FromForm, Debug)]
pub struct GraphQLQuery {
query: String,
#[field(name = "operationName")]
operation_name: Option<String>,
variables: Option<String>,
}
impl GraphQLQuery {
pub async fn execute<Query, Mutation, Subscription>(
self,
schema: &Schema<Query, Mutation, Subscription>,
) -> GraphQLResponse
where
Query: ObjectType + 'static,
Mutation: ObjectType + 'static,
Subscription: SubscriptionType + 'static,
{
let request: GraphQLRequest = self.into();
request.execute(schema).await
}
}
#[rocket::async_trait]
impl<'r> FromData<'r> for GraphQLRequest {
type Error = ParseRequestError;
async fn from_data(req: &'r rocket::Request<'_>, data: Data<'r>) -> data::Outcome<'r, Self> {
GraphQLBatchRequest::from_data(req, data)
.await
.and_then(|request| match request.0.into_single() {
Ok(single) => data::Outcome::Success(Self(single)),
Err(e) => data::Outcome::Failure((Status::BadRequest, e)),
})
}
}
#[derive(Debug)]
pub struct GraphQLResponse(pub async_graphql::BatchResponse);
impl From<async_graphql::BatchResponse> for GraphQLResponse {
fn from(batch: async_graphql::BatchResponse) -> Self {
Self(batch)
}
}
impl From<async_graphql::Response> for GraphQLResponse {
fn from(res: async_graphql::Response) -> Self {
Self(res.into())
}
}
impl<'r> Responder<'r, 'static> for GraphQLResponse {
fn respond_to(self, _: &'r rocket::Request<'_>) -> response::Result<'static> {
let body = serde_json::to_string(&self.0).unwrap();
let mut response = rocket::Response::new();
response.set_header(ContentType::new("application", "json"));
if self.0.is_ok() {
if let Some(cache_control) = self.0.cache_control().value() {
response.set_header(Header::new("cache-control", cache_control));
}
}
for (name, value) in self.0.http_headers() {
response.adjoin_header(Header::new(name.to_string(), value.to_string()));
}
response.set_sized_body(body.len(), Cursor::new(body));
Ok(response)
}
}