async-graphql/src/query.rs

192 lines
6.4 KiB
Rust
Raw Normal View History

2020-03-17 09:26:59 +00:00
use crate::context::Data;
2020-03-26 03:34:28 +00:00
use crate::extensions::BoxExtension;
2020-04-01 08:53:49 +00:00
use crate::registry::CacheControl;
use crate::{ContextBase, Error, OutputValueType, Result, Schema};
2020-04-01 08:53:49 +00:00
use crate::{ObjectType, QueryError, Variables};
2020-03-17 09:26:59 +00:00
use bytes::Bytes;
use graphql_parser::query::{
2020-04-01 08:53:49 +00:00
Definition, Document, OperationDefinition, SelectionSet, VariableDefinition,
2020-03-17 09:26:59 +00:00
};
use graphql_parser::Pos;
2020-03-31 03:19:18 +00:00
use std::any::Any;
2020-03-17 09:26:59 +00:00
use std::collections::HashMap;
2020-03-26 03:34:28 +00:00
use std::sync::atomic::AtomicUsize;
2020-03-17 09:26:59 +00:00
/// Query response
pub struct QueryResponse {
2020-04-01 08:53:49 +00:00
/// Data of query result
pub data: serde_json::Value,
/// Extensions result
pub extensions: Option<serde_json::Map<String, serde_json::Value>>,
2020-03-17 09:26:59 +00:00
}
/// Query builder
2020-04-01 08:53:49 +00:00
pub struct QueryBuilder<Query, Mutation, Subscription> {
pub(crate) schema: Schema<Query, Mutation, Subscription>,
2020-03-26 03:34:28 +00:00
pub(crate) extensions: Vec<BoxExtension>,
2020-04-01 08:53:49 +00:00
pub(crate) document: Document,
pub(crate) operation_name: Option<String>,
pub(crate) variables: Variables,
2020-03-31 03:19:18 +00:00
pub(crate) ctx_data: Option<Data>,
2020-04-01 08:53:49 +00:00
pub(crate) cache_control: CacheControl,
2020-03-17 09:26:59 +00:00
}
2020-04-01 08:53:49 +00:00
impl<Query, Mutation, Subscription> QueryBuilder<Query, Mutation, Subscription> {
fn current_operation(&self) -> Option<(&SelectionSet, &[VariableDefinition], bool)> {
for definition in &self.document.definitions {
2020-03-17 09:26:59 +00:00
match definition {
Definition::Operation(operation_definition) => match operation_definition {
OperationDefinition::SelectionSet(s) => {
2020-04-01 08:53:49 +00:00
return Some((s, &[], true));
2020-03-17 09:26:59 +00:00
}
OperationDefinition::Query(query)
2020-04-01 08:53:49 +00:00
if query.name.is_none()
|| query.name.as_deref() == self.operation_name.as_deref() =>
2020-03-17 09:26:59 +00:00
{
2020-04-01 08:53:49 +00:00
return Some((&query.selection_set, &query.variable_definitions, true));
2020-03-17 09:26:59 +00:00
}
OperationDefinition::Mutation(mutation)
if mutation.name.is_none()
2020-04-01 08:53:49 +00:00
|| mutation.name.as_deref() == self.operation_name.as_deref() =>
2020-03-17 09:26:59 +00:00
{
2020-04-01 08:53:49 +00:00
return Some((
&mutation.selection_set,
&mutation.variable_definitions,
false,
));
2020-03-17 09:26:59 +00:00
}
OperationDefinition::Subscription(subscription)
if subscription.name.is_none()
2020-04-01 08:53:49 +00:00
|| subscription.name.as_deref() == self.operation_name.as_deref() =>
2020-03-17 09:26:59 +00:00
{
2020-04-01 08:53:49 +00:00
return None;
2020-03-17 09:26:59 +00:00
}
_ => {}
},
2020-04-01 08:53:49 +00:00
Definition::Fragment(_) => {}
2020-03-17 09:26:59 +00:00
}
}
2020-04-01 08:53:49 +00:00
None
2020-03-17 09:26:59 +00:00
}
2020-04-01 08:53:49 +00:00
/// Specify the operation name.
pub fn operator_name<T: Into<String>>(self, name: T) -> Self {
QueryBuilder {
operation_name: Some(name.into()),
..self
}
2020-03-17 09:26:59 +00:00
}
2020-04-01 08:53:49 +00:00
/// Specify the variables.
pub fn variables(self, variables: Variables) -> Self {
QueryBuilder { variables, ..self }
}
2020-03-26 03:34:28 +00:00
2020-04-01 08:53:49 +00:00
/// Add a context data that can be accessed in the `Context`, you access it with `Context::data`.
pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
if let Some(ctx_data) = &mut self.ctx_data {
ctx_data.insert(data);
} else {
let mut ctx_data = Data::default();
ctx_data.insert(data);
self.ctx_data = Some(ctx_data);
}
self
}
2020-03-17 09:26:59 +00:00
/// Detects whether any parameter contains the Upload type
pub fn is_upload(&self) -> bool {
2020-04-01 08:53:49 +00:00
if let Some((_, variable_definitions, _)) = self.current_operation() {
2020-03-17 09:26:59 +00:00
for d in variable_definitions {
2020-04-01 08:53:49 +00:00
if let Some(ty) = self
.schema
.0
.registry
.basic_type_by_parsed_type(&d.var_type)
{
2020-03-17 09:26:59 +00:00
if ty.name() == "Upload" {
return true;
}
}
}
}
false
}
/// Set upload files
pub fn set_upload(
&mut self,
var_path: &str,
filename: &str,
content_type: Option<&str>,
content: Bytes,
) {
self.variables
.set_upload(var_path, filename, content_type, content);
}
/// Execute the query.
pub async fn execute(self) -> Result<QueryResponse>
2020-03-17 09:26:59 +00:00
where
2020-03-19 09:20:12 +00:00
Query: ObjectType + Send + Sync,
Mutation: ObjectType + Send + Sync,
2020-03-17 09:26:59 +00:00
{
2020-03-26 03:34:28 +00:00
let resolve_id = AtomicUsize::default();
2020-04-01 08:53:49 +00:00
let mut fragments = HashMap::new();
let (selection_set, variable_definitions, is_query) =
self.current_operation().ok_or_else(|| Error::Query {
pos: Pos::default(),
path: None,
err: QueryError::MissingOperation,
})?;
2020-04-01 08:53:49 +00:00
for definition in &self.document.definitions {
if let Definition::Fragment(fragment) = &definition {
fragments.insert(fragment.name.clone(), fragment.clone());
}
}
2020-03-17 09:26:59 +00:00
let ctx = ContextBase {
2020-03-26 10:30:29 +00:00
path_node: None,
2020-03-26 03:34:28 +00:00
resolve_id: &resolve_id,
extensions: &self.extensions,
2020-04-01 08:53:49 +00:00
item: selection_set,
2020-03-17 09:26:59 +00:00
variables: &self.variables,
2020-04-01 08:53:49 +00:00
variable_definitions,
registry: &self.schema.0.registry,
data: &self.schema.0.data,
2020-03-31 03:19:18 +00:00
ctx_data: self.ctx_data.as_ref(),
2020-04-01 08:53:49 +00:00
fragments: &fragments,
2020-03-17 09:26:59 +00:00
};
2020-03-26 03:34:28 +00:00
self.extensions.iter().for_each(|e| e.execution_start());
2020-04-01 08:53:49 +00:00
let data = if is_query {
OutputValueType::resolve(&self.schema.0.query, &ctx, selection_set.span.0).await?
2020-04-01 08:53:49 +00:00
} else {
OutputValueType::resolve(&self.schema.0.mutation, &ctx, selection_set.span.0).await?
2020-04-01 08:53:49 +00:00
};
2020-03-26 03:34:28 +00:00
self.extensions.iter().for_each(|e| e.execution_end());
let res = QueryResponse {
2020-03-26 03:34:28 +00:00
data,
extensions: if !self.extensions.is_empty() {
Some(
self.extensions
.iter()
.map(|e| (e.name().to_string(), e.result()))
2020-04-01 08:53:49 +00:00
.collect::<serde_json::Map<_, _>>(),
2020-03-26 03:34:28 +00:00
)
} else {
None
},
};
Ok(res)
2020-03-17 09:26:59 +00:00
}
2020-03-22 08:45:59 +00:00
/// Get cache control value
pub fn cache_control(&self) -> CacheControl {
self.cache_control
}
}