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
use crate::context::Data;
use crate::extensions::BoxExtension;
use crate::registry::CacheControl;
use crate::{ContextBase, Error, OutputValueType, Result, Schema};
use crate::{ObjectType, QueryError, Variables};
use bytes::Bytes;
use graphql_parser::query::{
Definition, Document, OperationDefinition, SelectionSet, VariableDefinition,
};
use graphql_parser::Pos;
use std::any::Any;
use std::collections::HashMap;
use std::sync::atomic::AtomicUsize;
pub struct QueryResponse {
pub data: serde_json::Value,
pub extensions: Option<serde_json::Map<String, serde_json::Value>>,
}
pub struct QueryBuilder<Query, Mutation, Subscription> {
pub(crate) schema: Schema<Query, Mutation, Subscription>,
pub(crate) extensions: Vec<BoxExtension>,
pub(crate) document: Document,
pub(crate) operation_name: Option<String>,
pub(crate) variables: Variables,
pub(crate) ctx_data: Option<Data>,
pub(crate) cache_control: CacheControl,
}
impl<Query, Mutation, Subscription> QueryBuilder<Query, Mutation, Subscription> {
fn current_operation(&self) -> Option<(&SelectionSet, &[VariableDefinition], bool)> {
for definition in &self.document.definitions {
match definition {
Definition::Operation(operation_definition) => match operation_definition {
OperationDefinition::SelectionSet(s) => {
return Some((s, &[], true));
}
OperationDefinition::Query(query)
if query.name.is_none()
|| query.name.as_deref() == self.operation_name.as_deref() =>
{
return Some((&query.selection_set, &query.variable_definitions, true));
}
OperationDefinition::Mutation(mutation)
if mutation.name.is_none()
|| mutation.name.as_deref() == self.operation_name.as_deref() =>
{
return Some((
&mutation.selection_set,
&mutation.variable_definitions,
false,
));
}
OperationDefinition::Subscription(subscription)
if subscription.name.is_none()
|| subscription.name.as_deref() == self.operation_name.as_deref() =>
{
return None;
}
_ => {}
},
Definition::Fragment(_) => {}
}
}
None
}
pub fn operator_name<T: Into<String>>(self, name: T) -> Self {
QueryBuilder {
operation_name: Some(name.into()),
..self
}
}
pub fn variables(self, variables: Variables) -> Self {
QueryBuilder { variables, ..self }
}
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
}
pub fn is_upload(&self) -> bool {
if let Some((_, variable_definitions, _)) = self.current_operation() {
for d in variable_definitions {
if let Some(ty) = self
.schema
.0
.registry
.basic_type_by_parsed_type(&d.var_type)
{
if ty.name() == "Upload" {
return true;
}
}
}
}
false
}
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);
}
pub async fn execute(self) -> Result<QueryResponse>
where
Query: ObjectType + Send + Sync,
Mutation: ObjectType + Send + Sync,
{
let resolve_id = AtomicUsize::default();
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,
})?;
for definition in &self.document.definitions {
if let Definition::Fragment(fragment) = &definition {
fragments.insert(fragment.name.clone(), fragment.clone());
}
}
let ctx = ContextBase {
path_node: None,
resolve_id: &resolve_id,
extensions: &self.extensions,
item: selection_set,
variables: &self.variables,
variable_definitions,
registry: &self.schema.0.registry,
data: &self.schema.0.data,
ctx_data: self.ctx_data.as_ref(),
fragments: &fragments,
};
self.extensions.iter().for_each(|e| e.execution_start());
let data = if is_query {
OutputValueType::resolve(&self.schema.0.query, &ctx, selection_set.span.0).await?
} else {
OutputValueType::resolve(&self.schema.0.mutation, &ctx, selection_set.span.0).await?
};
self.extensions.iter().for_each(|e| e.execution_end());
let res = QueryResponse {
data,
extensions: if !self.extensions.is_empty() {
Some(
self.extensions
.iter()
.map(|e| (e.name().to_string(), e.result()))
.collect::<serde_json::Map<_, _>>(),
)
} else {
None
},
};
Ok(res)
}
pub fn cache_control(&self) -> CacheControl {
self.cache_control
}
}