async-graphql/src/extensions/mod.rs

200 lines
5.8 KiB
Rust
Raw Normal View History

2020-03-26 03:34:28 +00:00
//! Extensions for schema
2020-09-14 18:38:41 +00:00
#[cfg(feature = "apollo_tracing")]
2020-04-28 07:01:19 +00:00
mod apollo_tracing;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "log")]
2020-05-22 03:58:49 +00:00
mod logger;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "tracing")]
2020-03-26 03:34:28 +00:00
mod tracing;
2020-04-28 07:01:19 +00:00
use crate::context::{QueryPathNode, ResolveId};
use crate::{FieldResult, QueryEnv, Result, SchemaEnv, Variables};
2020-05-22 03:58:49 +00:00
2020-09-14 18:38:41 +00:00
#[cfg(feature = "apollo_tracing")]
2020-05-22 03:58:49 +00:00
pub use self::apollo_tracing::ApolloTracing;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "log")]
2020-05-22 03:58:49 +00:00
pub use self::logger::Logger;
2020-09-14 18:38:41 +00:00
#[cfg(feature = "tracing")]
2020-05-22 03:58:49 +00:00
pub use self::tracing::Tracing;
use crate::parser::types::ExecutableDocument;
2020-05-22 03:58:49 +00:00
use crate::Error;
use serde_json::Value;
use std::any::{Any, TypeId};
2020-03-26 03:34:28 +00:00
pub(crate) type BoxExtension = Box<dyn Extension>;
2020-05-22 03:58:49 +00:00
#[doc(hidden)]
pub struct Extensions(pub(crate) Vec<BoxExtension>);
2020-03-26 03:34:28 +00:00
/// Parameters for `Extension::resolve_field_start`
pub struct ResolveInfo<'a> {
/// Because resolver is concurrent, `Extension::resolve_field_start` and `Extension::resolve_field_end` are
/// not strictly ordered, so each pair is identified by an id.
2020-04-28 07:01:19 +00:00
pub resolve_id: ResolveId,
2020-03-26 03:34:28 +00:00
2020-03-26 10:30:29 +00:00
/// Current path node, You can go through the entire path.
pub path_node: &'a QueryPathNode<'a>,
2020-03-26 03:34:28 +00:00
/// Parent type
pub parent_type: &'a str,
/// Current return type, is qualified name.
pub return_type: &'a str,
2020-09-26 07:52:59 +00:00
#[doc(hidden)]
pub schema_env: &'a SchemaEnv,
#[doc(hidden)]
pub query_env: &'a QueryEnv,
}
impl<'a> ResolveInfo<'a> {
/// Gets the global data defined in the `Context` or `Schema`.
///
/// If both `Schema` and `Query` have the same data type, the data in the `Query` is obtained.
///
/// # Errors
///
/// Returns a `FieldError` if the specified type data does not exist.
pub fn data<D: Any + Send + Sync>(&self) -> FieldResult<&D> {
self.data_opt::<D>()
.ok_or_else(|| format!("Data `{}` does not exist.", std::any::type_name::<D>()).into())
}
/// Gets the global data defined in the `Context` or `Schema`.
///
/// # Panics
///
/// It will panic if the specified data type does not exist.
pub fn data_unchecked<D: Any + Send + Sync>(&self) -> &D {
self.data_opt::<D>()
.unwrap_or_else(|| panic!("Data `{}` does not exist.", std::any::type_name::<D>()))
}
/// Gets the global data defined in the `Context` or `Schema` or `None` if the specified type data does not exist.
pub fn data_opt<D: Any + Send + Sync>(&self) -> Option<&D> {
self.query_env
.ctx_data
.get(&TypeId::of::<D>())
.or_else(|| self.schema_env.data.get(&TypeId::of::<D>()))
.and_then(|d| d.downcast_ref::<D>())
}
2020-03-26 03:34:28 +00:00
}
/// Represents a GraphQL extension
#[allow(unused_variables)]
pub trait Extension: Sync + Send + 'static {
2020-04-28 07:01:19 +00:00
/// If this extension needs to output data to query results, you need to specify a name.
fn name(&self) -> Option<&'static str> {
None
}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the parse.
fn parse_start(&mut self, query_source: &str, variables: &Variables) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the parse.
fn parse_end(&mut self, document: &ExecutableDocument) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the validation.
fn validation_start(&mut self) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the validation.
fn validation_end(&mut self) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the execution.
fn execution_start(&mut self) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the execution.
fn execution_end(&mut self) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the resolve field.
fn resolve_start(&mut self, info: &ResolveInfo<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the resolve field.
fn resolve_end(&mut self, info: &ResolveInfo<'_>) {}
2020-05-22 03:58:49 +00:00
/// Called when an error occurs.
fn error(&mut self, err: &Error) {}
2020-03-26 03:34:28 +00:00
/// Get the results
fn result(&mut self) -> Option<serde_json::Value> {
2020-04-28 07:01:19 +00:00
None
}
2020-03-26 03:34:28 +00:00
}
2020-05-22 03:58:49 +00:00
pub(crate) trait ErrorLogger {
fn log_error(self, extensions: &spin::Mutex<Extensions>) -> Self;
}
impl<T> ErrorLogger for Result<T> {
fn log_error(self, extensions: &spin::Mutex<Extensions>) -> Self {
if let Err(err) = &self {
extensions.lock().error(err);
2020-05-22 03:58:49 +00:00
}
self
2020-05-22 03:58:49 +00:00
}
}
impl Extension for Extensions {
fn parse_start(&mut self, query_source: &str, variables: &Variables) {
self.0
.iter_mut()
.for_each(|e| e.parse_start(query_source, variables));
2020-05-22 03:58:49 +00:00
}
fn parse_end(&mut self, document: &ExecutableDocument) {
self.0.iter_mut().for_each(|e| e.parse_end(document));
2020-05-22 03:58:49 +00:00
}
fn validation_start(&mut self) {
self.0.iter_mut().for_each(|e| e.validation_start());
2020-05-22 03:58:49 +00:00
}
fn validation_end(&mut self) {
self.0.iter_mut().for_each(|e| e.validation_end());
2020-05-22 03:58:49 +00:00
}
fn execution_start(&mut self) {
self.0.iter_mut().for_each(|e| e.execution_start());
2020-05-22 03:58:49 +00:00
}
fn execution_end(&mut self) {
self.0.iter_mut().for_each(|e| e.execution_end());
2020-05-22 03:58:49 +00:00
}
fn resolve_start(&mut self, info: &ResolveInfo<'_>) {
self.0.iter_mut().for_each(|e| e.resolve_start(info));
2020-05-22 03:58:49 +00:00
}
fn resolve_end(&mut self, resolve_id: &ResolveInfo<'_>) {
self.0.iter_mut().for_each(|e| e.resolve_end(resolve_id));
2020-05-22 03:58:49 +00:00
}
fn error(&mut self, err: &Error) {
self.0.iter_mut().for_each(|e| e.error(err));
2020-05-22 03:58:49 +00:00
}
fn result(&mut self) -> Option<Value> {
2020-05-22 03:58:49 +00:00
if !self.0.is_empty() {
let value = self
.0
.iter_mut()
2020-05-22 03:58:49 +00:00
.filter_map(|e| {
if let Some(name) = e.name() {
e.result().map(|res| (name.to_string(), res))
} else {
None
}
})
.collect::<serde_json::Map<_, _>>();
if value.is_empty() {
None
} else {
Some(value.into())
}
} else {
None
}
}
}