async-graphql/src/extensions/mod.rs

223 lines
6.7 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};
2020-09-29 12:47:37 +00:00
use crate::{Data, FieldResult, Result, 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-09-29 12:47:37 +00:00
/// Context for extension
pub struct ExtensionContext<'a> {
2020-09-26 07:52:59 +00:00
#[doc(hidden)]
2020-09-29 12:47:37 +00:00
pub schema_data: &'a Data,
2020-09-26 07:52:59 +00:00
#[doc(hidden)]
2020-09-29 12:47:37 +00:00
pub query_data: &'a Data,
}
2020-09-29 12:47:37 +00:00
impl<'a> ExtensionContext<'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> {
2020-09-29 12:47:37 +00:00
self.query_data
.get(&TypeId::of::<D>())
2020-09-29 12:47:37 +00:00
.or_else(|| self.schema_data.get(&TypeId::of::<D>()))
.and_then(|d| d.downcast_ref::<D>())
}
2020-03-26 03:34:28 +00:00
}
2020-09-29 12:47:37 +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.
pub resolve_id: ResolveId,
/// Current path node, You can go through the entire path.
pub path_node: &'a QueryPathNode<'a>,
/// Parent type
pub parent_type: &'a str,
/// Current return type, is qualified name.
pub return_type: &'a str,
}
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.
2020-09-29 12:47:37 +00:00
fn parse_start(
&mut self,
ctx: &ExtensionContext<'_>,
query_source: &str,
variables: &Variables,
) {
}
2020-03-26 03:34:28 +00:00
/// Called at the end of the parse.
2020-09-29 12:47:37 +00:00
fn parse_end(&mut self, ctx: &ExtensionContext<'_>, document: &ExecutableDocument) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the validation.
2020-09-29 12:47:37 +00:00
fn validation_start(&mut self, ctx: &ExtensionContext<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the validation.
2020-09-29 12:47:37 +00:00
fn validation_end(&mut self, ctx: &ExtensionContext<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the execution.
2020-09-29 12:47:37 +00:00
fn execution_start(&mut self, ctx: &ExtensionContext<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the execution.
2020-09-29 12:47:37 +00:00
fn execution_end(&mut self, ctx: &ExtensionContext<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the begin of the resolve field.
2020-09-29 12:47:37 +00:00
fn resolve_start(&mut self, ctx: &ExtensionContext<'_>, info: &ResolveInfo<'_>) {}
2020-03-26 03:34:28 +00:00
/// Called at the end of the resolve field.
2020-09-29 12:47:37 +00:00
fn resolve_end(&mut self, ctx: &ExtensionContext<'_>, info: &ResolveInfo<'_>) {}
2020-05-22 03:58:49 +00:00
/// Called when an error occurs.
2020-09-29 12:47:37 +00:00
fn error(&mut self, ctx: &ExtensionContext<'_>, err: &Error) {}
2020-03-26 03:34:28 +00:00
/// Get the results
2020-09-29 12:47:37 +00:00
fn result(&mut self, ctx: &ExtensionContext<'_>) -> 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 {
2020-09-29 12:47:37 +00:00
fn log_error(self, ctx: &ExtensionContext<'_>, extensions: &spin::Mutex<Extensions>) -> Self;
}
impl<T> ErrorLogger for Result<T> {
2020-09-29 12:47:37 +00:00
fn log_error(self, ctx: &ExtensionContext<'_>, extensions: &spin::Mutex<Extensions>) -> Self {
if let Err(err) = &self {
2020-09-29 12:47:37 +00:00
extensions.lock().error(ctx, err);
2020-05-22 03:58:49 +00:00
}
self
2020-05-22 03:58:49 +00:00
}
}
impl Extension for Extensions {
2020-09-29 12:47:37 +00:00
fn parse_start(
&mut self,
ctx: &ExtensionContext<'_>,
query_source: &str,
variables: &Variables,
) {
self.0
.iter_mut()
2020-09-29 12:47:37 +00:00
.for_each(|e| e.parse_start(ctx, query_source, variables));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn parse_end(&mut self, ctx: &ExtensionContext<'_>, document: &ExecutableDocument) {
self.0.iter_mut().for_each(|e| e.parse_end(ctx, document));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn validation_start(&mut self, ctx: &ExtensionContext<'_>) {
self.0.iter_mut().for_each(|e| e.validation_start(ctx));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn validation_end(&mut self, ctx: &ExtensionContext<'_>) {
self.0.iter_mut().for_each(|e| e.validation_end(ctx));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn execution_start(&mut self, ctx: &ExtensionContext<'_>) {
self.0.iter_mut().for_each(|e| e.execution_start(ctx));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn execution_end(&mut self, ctx: &ExtensionContext<'_>) {
self.0.iter_mut().for_each(|e| e.execution_end(ctx));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn resolve_start(&mut self, ctx: &ExtensionContext<'_>, info: &ResolveInfo<'_>) {
self.0.iter_mut().for_each(|e| e.resolve_start(ctx, info));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn resolve_end(&mut self, ctx: &ExtensionContext<'_>, resolve_id: &ResolveInfo<'_>) {
self.0
.iter_mut()
.for_each(|e| e.resolve_end(ctx, resolve_id));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn error(&mut self, ctx: &ExtensionContext<'_>, err: &Error) {
self.0.iter_mut().for_each(|e| e.error(ctx, err));
2020-05-22 03:58:49 +00:00
}
2020-09-29 12:47:37 +00:00
fn result(&mut self, ctx: &ExtensionContext<'_>) -> 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() {
2020-09-29 12:47:37 +00:00
e.result(ctx).map(|res| (name.to_string(), res))
2020-05-22 03:58:49 +00:00
} else {
None
}
})
.collect::<serde_json::Map<_, _>>();
if value.is_empty() {
None
} else {
Some(value.into())
}
} else {
None
}
}
}
2020-09-29 12:47:37 +00:00
/// Extension factory
///
/// Used to create an extension instance.
pub trait ExtensionFactory: Send + Sync + 'static {
/// Create an extended instance.
fn create(&self) -> Box<dyn Extension>;
}