async-graphql/src/schema.rs

292 lines
9.5 KiB
Rust
Raw Normal View History

2020-03-05 00:39:56 +00:00
use crate::context::Data;
use crate::model::__DirectiveLocation;
use crate::registry::{Directive, InputValue, Registry};
2020-03-03 11:15:18 +00:00
use crate::types::QueryRoot;
2020-03-08 12:35:36 +00:00
use crate::validation::check_rules;
2020-03-01 10:54:34 +00:00
use crate::{
2020-03-05 07:50:57 +00:00
ContextBase, GQLObject, GQLOutputValue, GQLType, QueryError, QueryParseError, Result, Variables,
2020-03-01 10:54:34 +00:00
};
use graphql_parser::parse_query;
2020-03-14 03:46:20 +00:00
use graphql_parser::query::{
Definition, FragmentDefinition, OperationDefinition, SelectionSet, VariableDefinition,
};
2020-03-05 00:39:56 +00:00
use std::any::Any;
2020-03-05 07:50:57 +00:00
use std::collections::HashMap;
2020-03-01 10:54:34 +00:00
2020-03-09 10:05:52 +00:00
/// GraphQL schema
2020-03-03 11:15:18 +00:00
pub struct Schema<Query, Mutation> {
2020-03-05 00:39:56 +00:00
query: QueryRoot<Query>,
mutation: Mutation,
2020-03-03 11:15:18 +00:00
registry: Registry,
2020-03-05 00:39:56 +00:00
data: Data,
2020-03-01 10:54:34 +00:00
}
2020-03-03 11:15:18 +00:00
impl<Query: GQLObject, Mutation: GQLObject> Schema<Query, Mutation> {
2020-03-09 10:05:52 +00:00
/// Create a schema.
///
/// The root object for the query and Mutation needs to be specified.
/// If there is no mutation, you can use `GQLEmptyMutation`.
2020-03-05 00:39:56 +00:00
pub fn new(query: Query, mutation: Mutation) -> Self {
2020-03-08 12:35:36 +00:00
let mut registry = Registry {
types: Default::default(),
directives: Default::default(),
implements: Default::default(),
query_type: Query::type_name().to_string(),
mutation_type: if Mutation::is_empty() {
None
} else {
Some(Mutation::type_name().to_string())
},
};
registry.add_directive(Directive {
name: "include",
description: Some("Directs the executor to include this field or fragment only when the `if` argument is true."),
2020-03-05 13:34:31 +00:00
locations: vec![
__DirectiveLocation::FIELD,
__DirectiveLocation::FRAGMENT_SPREAD,
__DirectiveLocation::INLINE_FRAGMENT
],
2020-03-08 12:35:36 +00:00
args: {
let mut args = HashMap::new();
args.insert("if", InputValue {
name: "if",
description: Some("Included when true."),
ty: "Boolean!".to_string(),
default_value: None
});
args
}
});
registry.add_directive(Directive {
name: "skip",
description: Some("Directs the executor to skip this field or fragment when the `if` argument is true."),
2020-03-05 13:34:31 +00:00
locations: vec![
__DirectiveLocation::FIELD,
__DirectiveLocation::FRAGMENT_SPREAD,
__DirectiveLocation::INLINE_FRAGMENT
],
2020-03-08 12:35:36 +00:00
args: {
let mut args = HashMap::new();
args.insert("if", InputValue {
name: "if",
description: Some("Skipped when true."),
ty: "Boolean!".to_string(),
default_value: None
});
args
}
});
// register scalars
bool::create_type_info(&mut registry);
i32::create_type_info(&mut registry);
f32::create_type_info(&mut registry);
String::create_type_info(&mut registry);
2020-03-08 12:35:36 +00:00
QueryRoot::<Query>::create_type_info(&mut registry);
2020-03-05 09:06:14 +00:00
if !Mutation::is_empty() {
Mutation::create_type_info(&mut registry);
}
2020-03-01 10:54:34 +00:00
Self {
2020-03-08 12:35:36 +00:00
query: QueryRoot { inner: query },
2020-03-01 10:54:34 +00:00
mutation,
2020-03-05 00:39:56 +00:00
registry,
data: Default::default(),
}
}
2020-03-09 10:05:52 +00:00
/// Add a global data that can be accessed in the `Context`.
2020-03-05 00:39:56 +00:00
pub fn data<D: Any + Send + Sync>(mut self, data: D) -> Self {
2020-03-08 01:21:29 +00:00
self.data.insert(data);
2020-03-05 00:39:56 +00:00
self
}
2020-03-09 10:05:52 +00:00
/// Start a query and return `QueryBuilder`.
2020-03-05 00:39:56 +00:00
pub fn query<'a>(&'a self, query_source: &'a str) -> QueryBuilder<'a, Query, Mutation> {
QueryBuilder {
query: &self.query,
mutation: &self.mutation,
2020-03-03 11:15:18 +00:00
registry: &self.registry,
2020-03-01 10:54:34 +00:00
query_source,
operation_name: None,
variables: None,
2020-03-05 00:39:56 +00:00
data: &self.data,
2020-03-01 10:54:34 +00:00
}
}
2020-03-03 11:15:18 +00:00
}
2020-03-14 03:46:20 +00:00
enum Root<'a, Query, Mutation> {
Query(&'a QueryRoot<Query>),
Mutation(&'a Mutation),
}
2020-03-09 10:05:52 +00:00
/// Query builder
2020-03-03 11:15:18 +00:00
pub struct QueryBuilder<'a, Query, Mutation> {
2020-03-05 00:39:56 +00:00
query: &'a QueryRoot<Query>,
mutation: &'a Mutation,
2020-03-03 11:15:18 +00:00
registry: &'a Registry,
query_source: &'a str,
operation_name: Option<&'a str>,
2020-03-14 03:46:20 +00:00
variables: Option<Variables>,
2020-03-05 00:39:56 +00:00
data: &'a Data,
2020-03-03 11:15:18 +00:00
}
2020-03-01 10:54:34 +00:00
2020-03-03 11:15:18 +00:00
impl<'a, Query, Mutation> QueryBuilder<'a, Query, Mutation> {
2020-03-09 10:05:52 +00:00
/// Specify the operation name.
2020-03-01 10:54:34 +00:00
pub fn operator_name(self, name: &'a str) -> Self {
2020-03-01 13:35:39 +00:00
QueryBuilder {
2020-03-01 10:54:34 +00:00
operation_name: Some(name),
..self
}
}
2020-03-09 10:05:52 +00:00
/// Specify the variables.
2020-03-14 03:46:20 +00:00
pub fn variables(self, vars: Variables) -> Self {
2020-03-01 13:35:39 +00:00
QueryBuilder {
2020-03-01 10:54:34 +00:00
variables: Some(vars),
..self
}
}
2020-03-14 03:46:20 +00:00
/// Prepare query
pub fn prepare(self) -> Result<PreparedQuery<'a, Query, Mutation>> {
2020-03-01 10:54:34 +00:00
let document =
2020-03-01 13:35:39 +00:00
parse_query(self.query_source).map_err(|err| QueryParseError(err.to_string()))?;
2020-03-05 07:50:57 +00:00
2020-03-08 12:35:36 +00:00
check_rules(self.registry, &document)?;
2020-03-14 03:46:20 +00:00
let mut fragments = HashMap::new();
let mut selection_set = None;
let mut variable_definitions = None;
let mut root = None;
2020-03-01 10:54:34 +00:00
2020-03-14 03:46:20 +00:00
for definition in document.definitions {
2020-03-01 10:54:34 +00:00
match definition {
2020-03-14 03:46:20 +00:00
Definition::Operation(operation_definition) => match operation_definition {
OperationDefinition::SelectionSet(s) => {
selection_set = Some(s);
root = Some(Root::Query(self.query));
break;
2020-03-01 10:54:34 +00:00
}
2020-03-14 03:46:20 +00:00
OperationDefinition::Query(query)
if query.name.is_none() || query.name.as_deref() == self.operation_name =>
2020-03-01 10:54:34 +00:00
{
2020-03-14 03:46:20 +00:00
selection_set = Some(query.selection_set);
variable_definitions = Some(query.variable_definitions);
root = Some(Root::Query(self.query));
break;
2020-03-01 10:54:34 +00:00
}
2020-03-14 03:46:20 +00:00
OperationDefinition::Mutation(mutation)
if mutation.name.is_none()
|| mutation.name.as_deref() == self.operation_name =>
{
selection_set = Some(mutation.selection_set);
variable_definitions = Some(mutation.variable_definitions);
root = Some(Root::Mutation(self.mutation));
break;
}
OperationDefinition::Subscription(subscription)
if subscription.name.is_none()
|| subscription.name.as_deref() == self.operation_name =>
2020-03-01 10:54:34 +00:00
{
2020-03-14 03:46:20 +00:00
return Err(QueryError::NotSupported.into());
2020-03-01 10:54:34 +00:00
}
2020-03-14 03:46:20 +00:00
_ => {}
},
Definition::Fragment(fragment) => {
fragments.insert(fragment.name.clone(), fragment);
2020-03-01 10:54:34 +00:00
}
}
}
2020-03-14 03:46:20 +00:00
Ok(PreparedQuery {
registry: self.registry,
variables: self.variables.unwrap_or_default(),
data: self.data,
fragments,
selection_set: selection_set.ok_or({
if let Some(name) = self.operation_name {
QueryError::UnknownOperationNamed {
name: name.to_string(),
}
} else {
QueryError::MissingOperation
}
})?,
root: root.unwrap(),
variable_definitions,
})
}
/// Execute the query.
pub async fn execute(self) -> Result<serde_json::Value>
where
Query: GQLObject + Send + Sync,
Mutation: GQLObject + Send + Sync,
{
self.prepare()?.execute().await
}
}
pub struct PreparedQuery<'a, Query, Mutation> {
root: Root<'a, Query, Mutation>,
registry: &'a Registry,
variables: Variables,
data: &'a Data,
fragments: HashMap<String, FragmentDefinition>,
selection_set: SelectionSet,
variable_definitions: Option<Vec<VariableDefinition>>,
}
impl<'a, Query, Mutation> PreparedQuery<'a, Query, Mutation> {
/// Detects whether any parameter contains the Upload type
pub fn is_upload(&self) -> bool {
if let Some(variable_definitions) = &self.variable_definitions {
for d in variable_definitions {
if let Some(ty) = self.registry.basic_type_by_parsed_type(&d.var_type) {
if ty.name() == "Upload" {
return true;
}
}
}
2020-03-01 10:54:34 +00:00
}
2020-03-14 03:46:20 +00:00
false
}
/// Set upload files
pub fn set_upload(
&mut self,
var_path: &str,
filename: &str,
content_type: Option<&str>,
content: Vec<u8>,
) {
self.variables
.set_upload(var_path, filename, content_type, content);
}
/// Execute the query.
pub async fn execute(self) -> Result<serde_json::Value>
where
Query: GQLObject + Send + Sync,
Mutation: GQLObject + Send + Sync,
{
let ctx = ContextBase {
item: &self.selection_set,
variables: &self.variables,
variable_definitions: self.variable_definitions.as_deref(),
registry: self.registry.clone(),
data: self.data,
fragments: &self.fragments,
};
2020-03-01 10:54:34 +00:00
2020-03-14 03:46:20 +00:00
match self.root {
Root::Query(query) => return GQLOutputValue::resolve(query, &ctx).await,
Root::Mutation(mutation) => return GQLOutputValue::resolve(mutation, &ctx).await,
}
2020-03-01 10:54:34 +00:00
}
}