Struct async_graphql::Response
source · #[non_exhaustive]pub struct Response {
pub data: Value,
pub extensions: BTreeMap<String, Value>,
pub cache_control: CacheControl,
pub errors: Vec<ServerError>,
pub http_headers: HeaderMap,
}
Expand description
Query response
Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional
Struct { .. }
syntax; cannot be matched against without a wildcard ..
; and struct update syntax will not work.data: Value
Data of query result
extensions: BTreeMap<String, Value>
Extensions result
cache_control: CacheControl
Cache control value
errors: Vec<ServerError>
Errors
http_headers: HeaderMap
HTTP headers
Implementations§
source§impl Response
impl Response
sourcepub fn new(data: impl Into<Value>) -> Self
pub fn new(data: impl Into<Value>) -> Self
Create a new successful response with the data.
Examples found in repository?
src/dynamic/schema.rs (line 312)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
async fn execute_once(&self, env: QueryEnv, root_value: &FieldValue<'static>) -> Response {
// execute
let ctx = env.create_context(&self.0.env, None, &env.operation.node.selection_set);
let res = match &env.operation.node.ty {
OperationType::Query => {
async move { self.query_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, false)
})
.await
}
OperationType::Mutation => {
async move { self.mutation_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, true)
})
.await
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value.unwrap_or_default()),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
More examples
src/schema.rs (line 471)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
async fn execute_once(&self, env: QueryEnv) -> Response {
// execute
let ctx = ContextBase {
path_node: None,
is_for_introspection: false,
item: &env.operation.node.selection_set,
schema_env: &self.0.env,
query_env: &env,
};
let res = match &env.operation.node.ty {
OperationType::Query => resolve_container(&ctx, &self.0.query).await,
OperationType::Mutation => {
if self.0.env.registry.introspection_mode == IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
resolve_container_serial(&ctx, &EmptyMutation).await
} else {
resolve_container_serial(&ctx, &self.0.mutation).await
}
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
sourcepub fn from_errors(errors: Vec<ServerError>) -> Self
pub fn from_errors(errors: Vec<ServerError>) -> Self
Create a response from some errors.
Examples found in repository?
src/types/empty_subscription.rs (line 49)
40 41 42 43 44 45 46 47 48 49 50 51
fn create_field_stream<'a>(
&'a self,
_ctx: &'a Context<'_>,
) -> Option<Pin<Box<dyn Stream<Item = Response> + Send + 'a>>>
where
Self: Send + Sync + 'static + Sized,
{
Some(Box::pin(stream::once(async move {
let err = ServerError::new("Schema is not configured for subscription.", None);
Response::from_errors(vec![err])
})))
}
More examples
src/dynamic/schema.rs (line 313)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
async fn execute_once(&self, env: QueryEnv, root_value: &FieldValue<'static>) -> Response {
// execute
let ctx = env.create_context(&self.0.env, None, &env.operation.node.selection_set);
let res = match &env.operation.node.ty {
OperationType::Query => {
async move { self.query_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, false)
})
.await
}
OperationType::Mutation => {
async move { self.mutation_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, true)
})
.await
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value.unwrap_or_default()),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
/// Execute a GraphQL query.
pub async fn execute(&self, request: impl Into<DynamicRequest>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
let request_fut = {
let extensions = extensions.clone();
async move {
match prepare_request(
extensions,
request.inner,
Default::default(),
&self.0.env.registry,
self.0.validation_mode,
self.0.recursive_depth,
self.0.complexity,
self.0.depth,
)
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone(), &request.root_value)
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
}
src/schema.rs (line 472)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
async fn execute_once(&self, env: QueryEnv) -> Response {
// execute
let ctx = ContextBase {
path_node: None,
is_for_introspection: false,
item: &env.operation.node.selection_set,
schema_env: &self.0.env,
query_env: &env,
};
let res = match &env.operation.node.ty {
OperationType::Query => resolve_container(&ctx, &self.0.query).await,
OperationType::Mutation => {
if self.0.env.registry.introspection_mode == IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
resolve_container_serial(&ctx, &EmptyMutation).await
} else {
resolve_container_serial(&ctx, &self.0.mutation).await
}
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
/// Execute a GraphQL query.
pub async fn execute(&self, request: impl Into<Request>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
let request_fut = {
let extensions = extensions.clone();
async move {
match prepare_request(
extensions,
request,
Default::default(),
&self.0.env.registry,
self.0.validation_mode,
self.0.recursive_depth,
self.0.complexity,
self.0.depth,
)
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone())
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
}
src/dynamic/subscription.rs (line 266)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
pub(crate) fn collect_streams<'a>(
&self,
schema: &Schema,
ctx: &ContextSelectionSet<'a>,
streams: &mut Vec<BoxFieldStream<'a>>,
root_value: &'a FieldValue<'static>,
) {
for selection in &ctx.item.node.items {
if let Selection::Field(field) = &selection.node {
if let Some(field_def) = self.fields.get(field.node.name.node.as_str()) {
let schema = schema.clone();
let field_type = field_def.ty.clone();
let resolver_fn = field_def.resolver_fn.clone();
let ctx = ctx.clone();
streams.push(
async_stream::try_stream! {
let ctx_field = ctx.with_field(field);
let field_name = ctx_field.item.node.response_key().node.clone();
let arguments = ObjectAccessor(Cow::Owned(
field
.node
.arguments
.iter()
.map(|(name, value)| {
ctx_field
.resolve_input_value(value.clone())
.map(|value| (name.node.clone(), value))
})
.collect::<ServerResult<IndexMap<Name, Value>>>()?,
));
let mut stream = resolver_fn(ResolverContext {
ctx: &ctx_field,
args: arguments,
parent_value: root_value,
})
.0
.await
.map_err(|err| ctx_field.set_error_path(err.into_server_error(ctx_field.item.pos)))?;
while let Some(value) = stream.next().await.transpose().map_err(|err| ctx_field.set_error_path(err.into_server_error(ctx_field.item.pos)))? {
let execute_fut = async {
let ri = ResolveInfo {
path_node: &QueryPathNode {
parent: None,
segment: QueryPathSegment::Name(&field_name),
},
parent_type: schema.0.env.registry.subscription_type.as_ref().unwrap(),
return_type: &field_type.to_string(),
name: field.node.name.node.as_str(),
alias: field.node.alias.as_ref().map(|alias| alias.node.as_str()),
is_for_introspection: false,
};
let resolve_fut = resolve(&schema, &ctx_field, &field_type.0, Some(&value));
futures_util::pin_mut!(resolve_fut);
let value = ctx_field.query_env.extensions.resolve(ri, &mut resolve_fut).await;
match value {
Ok(value) => {
let mut map = IndexMap::new();
map.insert(field_name.clone(), value.unwrap_or_default());
Response::new(Value::Object(map))
},
Err(err) => Response::from_errors(vec![err]),
}
};
futures_util::pin_mut!(execute_fut);
let resp = ctx_field.query_env.extensions.execute(ctx_field.query_env.operation_name.as_deref(), &mut execute_fut).await;
let is_err = !resp.errors.is_empty();
yield resp;
if is_err {
break;
}
}
}.map(|res| {
res.unwrap_or_else(|err| Response::from_errors(vec![err]))
})
.boxed(),
);
}
}
}
}
sourcepub fn extension(self, name: impl Into<String>, value: Value) -> Self
pub fn extension(self, name: impl Into<String>, value: Value) -> Self
Set the extension result of the response.
Examples found in repository?
src/extensions/analyzer.rs (lines 33-39)
29 30 31 32 33 34 35 36 37 38 39 40 41 42
async fn request(&self, ctx: &ExtensionContext<'_>, next: NextRequest<'_>) -> Response {
let mut resp = next.run(ctx).await;
let validation_result = self.validation_result.lock().await.take();
if let Some(validation_result) = validation_result {
resp = resp.extension(
"analyzer",
value! ({
"complexity": validation_result.complexity,
"depth": validation_result.depth,
}),
);
}
resp
}
More examples
src/extensions/apollo_tracing.rs (lines 89-100)
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
async fn execute(
&self,
ctx: &ExtensionContext<'_>,
operation_name: Option<&str>,
next: NextExecute<'_>,
) -> Response {
self.inner.lock().await.start_time = Utc::now();
let resp = next.run(ctx, operation_name).await;
let mut inner = self.inner.lock().await;
inner.end_time = Utc::now();
inner
.resolves
.sort_by(|a, b| a.start_offset.cmp(&b.start_offset));
resp.extension(
"tracing",
value!({
"version": 1,
"startTime": inner.start_time.to_rfc3339(),
"endTime": inner.end_time.to_rfc3339(),
"duration": (inner.end_time - inner.start_time).num_nanoseconds(),
"execution": {
"resolvers": inner.resolves
}
}),
)
}
sourcepub fn http_headers(self, http_headers: HeaderMap) -> Self
pub fn http_headers(self, http_headers: HeaderMap) -> Self
Set the http headers of the response.
Examples found in repository?
src/dynamic/schema.rs (line 315)
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
async fn execute_once(&self, env: QueryEnv, root_value: &FieldValue<'static>) -> Response {
// execute
let ctx = env.create_context(&self.0.env, None, &env.operation.node.selection_set);
let res = match &env.operation.node.ty {
OperationType::Query => {
async move { self.query_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, false)
})
.await
}
OperationType::Mutation => {
async move { self.mutation_root() }
.and_then(|query_root| {
resolve_container(self, query_root, &ctx, root_value, true)
})
.await
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value.unwrap_or_default()),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
More examples
src/schema.rs (line 474)
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
async fn execute_once(&self, env: QueryEnv) -> Response {
// execute
let ctx = ContextBase {
path_node: None,
is_for_introspection: false,
item: &env.operation.node.selection_set,
schema_env: &self.0.env,
query_env: &env,
};
let res = match &env.operation.node.ty {
OperationType::Query => resolve_container(&ctx, &self.0.query).await,
OperationType::Mutation => {
if self.0.env.registry.introspection_mode == IntrospectionMode::IntrospectionOnly
|| env.introspection_mode == IntrospectionMode::IntrospectionOnly
{
resolve_container_serial(&ctx, &EmptyMutation).await
} else {
resolve_container_serial(&ctx, &self.0.mutation).await
}
}
OperationType::Subscription => Err(ServerError::new(
"Subscriptions are not supported on this transport.",
None,
)),
};
let mut resp = match res {
Ok(value) => Response::new(value),
Err(err) => Response::from_errors(vec![err]),
}
.http_headers(std::mem::take(&mut *env.http_headers.lock().unwrap()));
resp.errors
.extend(std::mem::take(&mut *env.errors.lock().unwrap()));
resp
}
sourcepub fn cache_control(self, cache_control: CacheControl) -> Self
pub fn cache_control(self, cache_control: CacheControl) -> Self
Set the cache control of the response.
Examples found in repository?
src/schema.rs (line 504)
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
pub async fn execute(&self, request: impl Into<Request>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
let request_fut = {
let extensions = extensions.clone();
async move {
match prepare_request(
extensions,
request,
Default::default(),
&self.0.env.registry,
self.0.validation_mode,
self.0.recursive_depth,
self.0.complexity,
self.0.depth,
)
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone())
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
}
More examples
src/dynamic/schema.rs (line 345)
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
pub async fn execute(&self, request: impl Into<DynamicRequest>) -> Response {
let request = request.into();
let extensions = self.create_extensions(Default::default());
let request_fut = {
let extensions = extensions.clone();
async move {
match prepare_request(
extensions,
request.inner,
Default::default(),
&self.0.env.registry,
self.0.validation_mode,
self.0.recursive_depth,
self.0.complexity,
self.0.depth,
)
.await
{
Ok((env, cache_control)) => {
let fut = async {
self.execute_once(env.clone(), &request.root_value)
.await
.cache_control(cache_control)
};
futures_util::pin_mut!(fut);
env.extensions
.execute(env.operation_name.as_deref(), &mut fut)
.await
}
Err(errors) => Response::from_errors(errors),
}
}
};
futures_util::pin_mut!(request_fut);
extensions.request(&mut request_fut).await
}
sourcepub fn is_ok(&self) -> bool
pub fn is_ok(&self) -> bool
Returns true
if the response is ok.
Examples found in repository?
src/response.rs (line 89)
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
pub fn is_err(&self) -> bool {
!self.is_ok()
}
/// Extract the error from the response. Only if the `error` field is empty
/// will this return `Ok`.
#[inline]
pub fn into_result(self) -> Result<Self, Vec<ServerError>> {
if self.is_err() {
Err(self.errors)
} else {
Ok(self)
}
}
}
/// Response for batchable queries
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum BatchResponse {
/// Response for single queries
Single(Response),
/// Response for batch queries
Batch(Vec<Response>),
}
impl BatchResponse {
/// Gets cache control value
pub fn cache_control(&self) -> CacheControl {
match self {
BatchResponse::Single(resp) => resp.cache_control,
BatchResponse::Batch(resp) => resp.iter().fold(CacheControl::default(), |acc, item| {
acc.merge(&item.cache_control)
}),
}
}
/// Returns `true` if all responses are ok.
pub fn is_ok(&self) -> bool {
match self {
BatchResponse::Single(resp) => resp.is_ok(),
BatchResponse::Batch(resp) => resp.iter().all(Response::is_ok),
}
}
sourcepub fn is_err(&self) -> bool
pub fn is_err(&self) -> bool
Returns true
if the response is error.
Examples found in repository?
More examples
src/extensions/logger.rs (line 52)
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
async fn execute(
&self,
ctx: &ExtensionContext<'_>,
operation_name: Option<&str>,
next: NextExecute<'_>,
) -> Response {
let resp = next.run(ctx, operation_name).await;
if resp.is_err() {
for err in &resp.errors {
if !err.path.is_empty() {
let mut path = String::new();
for (idx, s) in err.path.iter().enumerate() {
if idx > 0 {
path.push('.');
}
match s {
PathSegment::Index(idx) => {
let _ = write!(&mut path, "{}", idx);
}
PathSegment::Field(name) => {
let _ = write!(&mut path, "{}", name);
}
}
}
log::info!(
target: "async-graphql",
"[Error] path={} message={}", path, err.message,
);
} else {
log::info!(
target: "async-graphql",
"[Error] message={}", err.message,
);
}
}
}
resp
}
sourcepub fn into_result(self) -> Result<Self, Vec<ServerError>>
pub fn into_result(self) -> Result<Self, Vec<ServerError>>
Extract the error from the response. Only if the error
field is empty
will this return Ok
.
Trait Implementations§
source§impl<'de> Deserialize<'de> for Response
impl<'de> Deserialize<'de> for Response
source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more