Skip to main content

oxidite_graphql/
context.rs

1use std::collections::HashMap;
2use oxidite_db::Database as OxiditeDatabase;
3
4/// GraphQL context that provides access to database and other resources
5pub struct Context {
6    pub database: Option<Box<dyn OxiditeDatabase>>,
7    pub extensions: HashMap<String, Box<dyn std::any::Any + Send + Sync>>,
8}
9
10impl Context {
11    pub fn new() -> Self {
12        Self {
13            database: None,
14            extensions: HashMap::new(),
15        }
16    }
17
18    pub fn with_database(mut self, db: Box<dyn OxiditeDatabase>) -> Self {
19        self.database = Some(db);
20        self
21    }
22
23    pub fn insert_extension<T: 'static + Send + Sync>(&mut self, key: String, value: T) {
24        self.extensions.insert(key, Box::new(value));
25    }
26
27    pub fn get_extension<T: 'static>(&self, key: &str) -> Option<&T> {
28        self.extensions.get(key).and_then(|boxed| boxed.downcast_ref::<T>())
29    }
30}
31
32impl Default for Context {
33    fn default() -> Self {
34        Self::new()
35    }
36}
37
38impl juniper::Context for Context {}