Avoid unnecessary Vec allocation when executing GraphQLBatchRequest (#638)

Additionally:
- make GraphQLBatchRequest/GraphQLBatchResponse code a bit more laconic
This commit is contained in:
Kai Ren 2020-04-28 07:08:27 +03:00 committed by GitHub
parent dc4cdf0bf5
commit 9064d7f523
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -249,13 +249,12 @@ where
SubscriptionT: crate::GraphQLType<S, Context = CtxT>, SubscriptionT: crate::GraphQLType<S, Context = CtxT>,
{ {
match *self { match *self {
GraphQLBatchRequest::Single(ref request) => { Self::Single(ref req) => {
GraphQLBatchResponse::Single(request.execute_sync(root_node, context)) GraphQLBatchResponse::Single(req.execute_sync(root_node, context))
} }
GraphQLBatchRequest::Batch(ref requests) => GraphQLBatchResponse::Batch( Self::Batch(ref reqs) => GraphQLBatchResponse::Batch(
requests reqs.iter()
.iter() .map(|req| req.execute_sync(root_node, context))
.map(|request| request.execute_sync(root_node, context))
.collect(), .collect(),
), ),
} }
@ -281,18 +280,16 @@ where
S: Send + Sync, S: Send + Sync,
{ {
match *self { match *self {
GraphQLBatchRequest::Single(ref request) => { Self::Single(ref req) => {
let res = request.execute(root_node, context).await; let resp = req.execute(root_node, context).await;
GraphQLBatchResponse::Single(res) GraphQLBatchResponse::Single(resp)
} }
GraphQLBatchRequest::Batch(ref requests) => { Self::Batch(ref reqs) => {
let futures = requests let resps = futures::future::join_all(
.iter() reqs.iter().map(|req| req.execute(root_node, context)),
.map(|request| request.execute(root_node, context)) )
.collect::<Vec<_>>(); .await;
let responses = futures::future::join_all(futures).await; GraphQLBatchResponse::Batch(resps)
GraphQLBatchResponse::Batch(responses)
} }
} }
} }
@ -300,10 +297,8 @@ where
/// The operation names of the request. /// The operation names of the request.
pub fn operation_names(&self) -> Vec<Option<&str>> { pub fn operation_names(&self) -> Vec<Option<&str>> {
match self { match self {
GraphQLBatchRequest::Single(req) => vec![req.operation_name()], Self::Single(req) => vec![req.operation_name()],
GraphQLBatchRequest::Batch(reqs) => { Self::Batch(reqs) => reqs.iter().map(|req| req.operation_name()).collect(),
reqs.iter().map(|req| req.operation_name()).collect()
}
} }
} }
} }
@ -333,8 +328,8 @@ where
/// you can use it to determine wheter to send a 200 or 400 HTTP status code. /// you can use it to determine wheter to send a 200 or 400 HTTP status code.
pub fn is_ok(&self) -> bool { pub fn is_ok(&self) -> bool {
match self { match self {
GraphQLBatchResponse::Single(res) => res.is_ok(), Self::Single(resp) => resp.is_ok(),
GraphQLBatchResponse::Batch(reses) => reses.iter().all(|res| res.is_ok()), Self::Batch(resps) => resps.iter().all(GraphQLResponse::is_ok),
} }
} }
} }