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
use crate::context::Data;
use crate::registry::{CacheControl, Registry};
use crate::types::QueryRoot;
use crate::validation::{check_rules, CheckResult};
use crate::{ContextBase, OutputValueType, Result, Schema};
use crate::{ObjectType, QueryError, QueryParseError, Variables};
use bytes::Bytes;
use graphql_parser::parse_query;
use graphql_parser::query::{
    Definition, FragmentDefinition, OperationDefinition, SelectionSet, VariableDefinition,
};
use std::collections::HashMap;

enum Root<'a, Query, Mutation> {
    Query(&'a QueryRoot<Query>),
    Mutation(&'a Mutation),
}

/// Query builder
pub struct QueryBuilder<'a, Query, Mutation, Subscription> {
    pub(crate) schema: &'a Schema<Query, Mutation, Subscription>,
    pub(crate) source: &'a str,
    pub(crate) operation_name: Option<&'a str>,
    pub(crate) variables: Option<Variables>,
    pub(crate) data: &'a Data,
}

impl<'a, Query, Mutation, Subscription> QueryBuilder<'a, Query, Mutation, Subscription> {
    /// Specify the operation name.
    pub fn operator_name(self, name: &'a str) -> Self {
        QueryBuilder {
            operation_name: Some(name),
            ..self
        }
    }

    /// Specify the variables.
    pub fn variables(self, vars: Variables) -> Self {
        QueryBuilder {
            variables: Some(vars),
            ..self
        }
    }

    /// Prepare query
    pub fn prepare(self) -> Result<PreparedQuery<'a, Query, Mutation>> {
        let document = parse_query(self.source).map_err(|err| QueryParseError(err.to_string()))?;
        let CheckResult {
            cache_control,
            complexity,
            depth,
        } = check_rules(&self.schema.registry, &document)?;

        if let Some(limit_complexity) = self.schema.complexity {
            if complexity > limit_complexity {
                return Err(QueryError::TooComplex.into());
            }
        }

        if let Some(limit_depth) = self.schema.depth {
            if depth > limit_depth {
                return Err(QueryError::TooDeep.into());
            }
        }

        let mut fragments = HashMap::new();
        let mut selection_set = None;
        let mut variable_definitions = None;
        let mut root = None;

        for definition in document.definitions {
            match definition {
                Definition::Operation(operation_definition) => match operation_definition {
                    OperationDefinition::SelectionSet(s) => {
                        selection_set = Some(s);
                        root = Some(Root::Query(&self.schema.query));
                    }
                    OperationDefinition::Query(query)
                        if query.name.is_none() || query.name.as_deref() == self.operation_name =>
                    {
                        selection_set = Some(query.selection_set);
                        variable_definitions = Some(query.variable_definitions);
                        root = Some(Root::Query(&self.schema.query));
                    }
                    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.schema.mutation));
                    }
                    OperationDefinition::Subscription(subscription)
                        if subscription.name.is_none()
                            || subscription.name.as_deref() == self.operation_name =>
                    {
                        return Err(QueryError::NotSupported.into());
                    }
                    _ => {}
                },
                Definition::Fragment(fragment) => {
                    fragments.insert(fragment.name.clone(), fragment);
                }
            }
        }

        Ok(PreparedQuery {
            registry: &self.schema.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,
            cache_control,
        })
    }

    /// Execute the query.
    pub async fn execute(self) -> Result<serde_json::Value>
    where
        Query: ObjectType + Send + Sync,
        Mutation: ObjectType + Send + Sync,
    {
        self.prepare()?.execute().await
    }
}

/// Prepared query object
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>>,
    cache_control: CacheControl,
}

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;
                    }
                }
            }
        }
        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<serde_json::Value>
    where
        Query: ObjectType + Send + Sync,
        Mutation: ObjectType + Send + Sync,
    {
        let ctx = ContextBase {
            item: &self.selection_set,
            variables: &self.variables,
            variable_definitions: self.variable_definitions.as_deref(),
            registry: self.registry,
            data: self.data,
            fragments: &self.fragments,
        };

        match self.root {
            Root::Query(query) => OutputValueType::resolve(query, &ctx).await,
            Root::Mutation(mutation) => OutputValueType::resolve(mutation, &ctx).await,
        }
    }

    /// Get cache control value
    pub fn cache_control(&self) -> CacheControl {
        self.cache_control
    }
}