diff --git a/src/context.rs b/src/context.rs index 197761e7..da2bcb6d 100644 --- a/src/context.rs +++ b/src/context.rs @@ -22,6 +22,28 @@ use crate::{ ServerResult, UploadValue, Value, }; +/// Data related functions of the context. +pub trait DataContext<'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 `Error` if the specified type data does not exist. + fn data(&self) -> Result<&'a D>; + + /// Gets the global data defined in the `Context` or `Schema`. + /// + /// # Panics + /// + /// It will panic if the specified data type does not exist. + fn data_unchecked(&self) -> &'a D; + + /// Gets the global data defined in the `Context` or `Schema` or `None` if the specified type data does not exist. + fn data_opt(&self) -> Option<&'a D>; +} + /// Schema/Context data. /// /// This is a type map, allowing you to store anything inside it. @@ -259,6 +281,20 @@ impl QueryEnv { } } +impl<'a, T> DataContext<'a> for ContextBase<'a, T> { + fn data(&self) -> Result<&'a D> { + ContextBase::data::(self) + } + + fn data_unchecked(&self) -> &'a D { + ContextBase::data_unchecked::(self) + } + + fn data_opt(&self) -> Option<&'a D> { + ContextBase::data_opt::(self) + } +} + impl<'a, T> ContextBase<'a, T> { #[doc(hidden)] pub fn with_field( diff --git a/src/extensions/mod.rs b/src/extensions/mod.rs index 0b12691d..52a2a311 100644 --- a/src/extensions/mod.rs +++ b/src/extensions/mod.rs @@ -30,8 +30,8 @@ use futures_util::stream::BoxStream; use crate::parser::types::ExecutableDocument; use crate::{ - Data, Error, QueryPathNode, Request, Response, Result, SchemaEnv, ServerError, ServerResult, - ValidationResult, Value, Variables, + Data, DataContext, Error, QueryPathNode, Request, Response, Result, SchemaEnv, ServerError, + ServerResult, ValidationResult, Value, Variables, }; /// Context for extension @@ -46,6 +46,20 @@ pub struct ExtensionContext<'a> { pub query_data: Option<&'a Data>, } +impl<'a> DataContext<'a> for ExtensionContext<'a> { + fn data(&self) -> Result<&'a D> { + ExtensionContext::data::(self) + } + + fn data_unchecked(&self) -> &'a D { + ExtensionContext::data_unchecked::(self) + } + + fn data_opt(&self) -> Option<&'a D> { + ExtensionContext::data_opt::(self) + } +} + impl<'a> ExtensionContext<'a> { /// Convert the specified [ExecutableDocument] into a query string. ///