dynamic_graphql/
data.rs

1use std::any::Any;
2use std::any::TypeId;
3
4use async_graphql::Context;
5use fnv::FnvHashMap;
6
7pub struct SchemaData(FnvHashMap<TypeId, Box<dyn Any + Sync + Send>>);
8
9impl SchemaData {
10    pub fn new() -> Self {
11        Self(Default::default())
12    }
13}
14
15impl Default for SchemaData {
16    fn default() -> Self {
17        Self::new()
18    }
19}
20
21impl SchemaData {
22    pub fn insert<T: Any + Sync + Send>(&mut self, value: T) {
23        self.0.insert(TypeId::of::<T>(), Box::new(value));
24    }
25    pub fn get<T: Any + Sync + Send>(&self) -> Option<&T> {
26        self.0
27            .get(&TypeId::of::<T>())
28            .and_then(|v| v.downcast_ref::<T>())
29    }
30    pub fn get_mut<T: Any + Sync + Send>(&mut self) -> Option<&mut T> {
31        self.0
32            .get_mut(&TypeId::of::<T>())
33            .and_then(|v| v.downcast_mut::<T>())
34    }
35    pub fn get_or_default<T: Any + Sync + Send + Default>(&mut self) -> &mut T {
36        self.0
37            .entry(TypeId::of::<T>())
38            .or_insert_with(|| Box::<T>::default())
39            .downcast_mut()
40            .unwrap()
41    }
42    pub fn get_mut_or_default<T: Any + Sync + Send + Default>(&mut self) -> &mut T {
43        self.0
44            .entry(TypeId::of::<T>())
45            .or_insert_with(|| Box::<T>::default())
46            .downcast_mut()
47            .unwrap()
48    }
49}
50
51pub trait GetSchemaData {
52    fn get_schema_data(&self) -> &SchemaData;
53}
54
55impl GetSchemaData for Context<'_> {
56    fn get_schema_data(&self) -> &SchemaData {
57        self.data_unchecked()
58    }
59}