Skip to main content

GraphQLContext

Struct GraphQLContext 

Source
pub struct GraphQLContext { /* private fields */ }
Expand description

GraphQL context for managing request-scoped data

Provides access to request information, user authentication state, data loaders for efficient batch loading, and custom data storage.

§Examples

use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();

// Set custom data
context.set_data("api_version".to_string(), json!("v1"));

// Get custom data
let version = context.get_data("api_version");
assert_eq!(version, Some(json!("v1")));

Implementations§

Source§

impl GraphQLContext

Source

pub fn new() -> Self

Create a new GraphQL context

§Examples
use reinhardt_graphql::context::GraphQLContext;

let context = GraphQLContext::new();
assert!(context.get_data("nonexistent").is_none());
Source

pub fn set_data(&self, key: String, value: Value)

Set custom data in the context

§Examples
use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();
context.set_data("user_id".to_string(), json!("123"));

assert_eq!(context.get_data("user_id"), Some(json!("123")));
Source

pub fn get_data(&self, key: &str) -> Option<Value>

Get custom data from the context

Returns None if the key does not exist. For GraphQL resolvers that require the data to be present, use require_data instead to get a proper GraphQL error.

§Examples
use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();
context.set_data("count".to_string(), json!(42));

assert_eq!(context.get_data("count"), Some(json!(42)));
assert_eq!(context.get_data("nonexistent"), None);
Source

pub fn require_data(&self, key: &str) -> Result<Value>

Get required custom data from the context, returning a GraphQL error if missing

This method should be used in GraphQL resolvers where the data is expected to be present. Instead of panicking on a missing key, it returns a descriptive async_graphql::Error that will be surfaced as a GraphQL error in the response.

§Examples
use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();
context.set_data("api_version".to_string(), json!("v1"));

// Successful lookup
let version = context.require_data("api_version");
assert!(version.is_ok());
assert_eq!(version.unwrap(), json!("v1"));

// Missing key returns an error
let missing = context.require_data("nonexistent");
assert!(missing.is_err());
Source

pub fn remove_data(&self, key: &str) -> Option<Value>

Remove custom data from the context

§Examples
use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();
context.set_data("temp".to_string(), json!("value"));

let removed = context.remove_data("temp");
assert_eq!(removed, Some(json!("value")));
assert_eq!(context.get_data("temp"), None);
Source

pub fn clear_data(&self)

Clear all custom data

§Examples
use reinhardt_graphql::context::GraphQLContext;
use serde_json::json;

let context = GraphQLContext::new();
context.set_data("key1".to_string(), json!("value1"));
context.set_data("key2".to_string(), json!("value2"));

context.clear_data();

assert_eq!(context.get_data("key1"), None);
assert_eq!(context.get_data("key2"), None);
Source

pub fn add_data_loader<T: DataLoader>(&self, loader: Arc<T>)

Add a data loader to the context

§Examples
use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
use async_trait::async_trait;
use std::sync::Arc;

struct SimpleLoader;

#[async_trait]
impl DataLoader for SimpleLoader {
    type Key = i32;
    type Value = String;

    async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(format!("Value {}", key))
    }

    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(keys.iter().map(|k| format!("Value {}", k)).collect())
    }
}

let context = GraphQLContext::new();
let loader = Arc::new(SimpleLoader);
context.add_data_loader(loader.clone());

let retrieved = context.get_data_loader::<SimpleLoader>();
assert!(retrieved.is_some());
Source

pub fn get_data_loader<T: DataLoader>(&self) -> Option<Arc<T>>

Get a data loader from the context

Returns None if the loader has not been registered. For GraphQL resolvers that require the loader, use require_data_loader instead to get a proper GraphQL error.

§Examples
use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
use async_trait::async_trait;
use std::sync::Arc;

struct TestLoader;

#[async_trait]
impl DataLoader for TestLoader {
    type Key = String;
    type Value = i32;

    async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(42)
    }

    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(vec![42; keys.len()])
    }
}

let context = GraphQLContext::new();
let loader = Arc::new(TestLoader);
context.add_data_loader(loader);

let retrieved = context.get_data_loader::<TestLoader>();
assert!(retrieved.is_some());
Source

pub fn require_data_loader<T: DataLoader>(&self) -> Result<Arc<T>>

Get a required data loader from the context, returning a GraphQL error if missing

This method should be used in GraphQL resolvers where the data loader is expected to be registered. Instead of panicking on a missing loader, it returns a descriptive async_graphql::Error that will be surfaced as a GraphQL error in the response.

§Examples
use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
use async_trait::async_trait;
use std::sync::Arc;

struct MyLoader;

#[async_trait]
impl DataLoader for MyLoader {
    type Key = String;
    type Value = i32;

    async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(42)
    }

    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(vec![42; keys.len()])
    }
}

let context = GraphQLContext::new();

// Missing loader returns an error
let result = context.require_data_loader::<MyLoader>();
assert!(result.is_err());

// After adding the loader, it succeeds
context.add_data_loader(Arc::new(MyLoader));
let result = context.require_data_loader::<MyLoader>();
assert!(result.is_ok());
Source

pub fn remove_data_loader<T: DataLoader>(&self)

Remove a data loader from the context

§Examples
use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
use async_trait::async_trait;
use std::sync::Arc;

struct RemovableLoader;

#[async_trait]
impl DataLoader for RemovableLoader {
    type Key = u64;
    type Value = String;

    async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(key.to_string())
    }

    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(keys.iter().map(|k| k.to_string()).collect())
    }
}

let context = GraphQLContext::new();
let loader = Arc::new(RemovableLoader);
context.add_data_loader(loader);

context.remove_data_loader::<RemovableLoader>();
assert!(context.get_data_loader::<RemovableLoader>().is_none());
Source

pub fn clear_loaders(&self)

Clear all data loaders

§Examples
use reinhardt_graphql::context::{GraphQLContext, DataLoader, LoaderError};
use async_trait::async_trait;
use std::sync::Arc;

struct Loader1;
struct Loader2;

#[async_trait]
impl DataLoader for Loader1 {
    type Key = i32;
    type Value = String;
    async fn load(&self, key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(key.to_string())
    }
    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(keys.iter().map(|k| k.to_string()).collect())
    }
}

#[async_trait]
impl DataLoader for Loader2 {
    type Key = String;
    type Value = i32;
    async fn load(&self, _key: Self::Key) -> Result<Self::Value, LoaderError> {
        Ok(0)
    }
    async fn load_many(&self, keys: Vec<Self::Key>) -> Result<Vec<Self::Value>, LoaderError> {
        Ok(vec![0; keys.len()])
    }
}

let context = GraphQLContext::new();
context.add_data_loader(Arc::new(Loader1));
context.add_data_loader(Arc::new(Loader2));

context.clear_loaders();

assert!(context.get_data_loader::<Loader1>().is_none());
assert!(context.get_data_loader::<Loader2>().is_none());

Trait Implementations§

Source§

impl Default for GraphQLContext

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more