dynamic_graphql/
instance.rs

1use std::borrow::Cow;
2
3use async_graphql::Context;
4use async_graphql::dynamic::FieldValue;
5
6use crate::any_box::AnyBox;
7use crate::registry::Registry;
8use crate::resolve::ResolveOwned;
9use crate::types::Interface;
10use crate::types::InterfaceMark;
11use crate::types::Object;
12use crate::types::OutputTypeName;
13use crate::types::Register;
14use crate::types::TypeName;
15
16pub struct Instance<'v, I, T = ()>
17where
18    I: ?Sized,
19    I: Interface,
20{
21    pub(crate) _interface: std::marker::PhantomData<I>,
22    pub(crate) _target: std::marker::PhantomData<T>,
23    value: AnyBox<'v>,
24}
25
26impl<I: ?Sized> Instance<'_, I>
27where
28    I: Interface,
29{
30    #[inline]
31    pub fn new_owned<'a, T>(value: T) -> Instance<'a, I>
32    where
33        T: InterfaceMark<I> + Object + Send + Sync + 'static,
34    {
35        Instance {
36            _interface: std::marker::PhantomData,
37            _target: std::marker::PhantomData,
38            value: AnyBox::new_owned(value, <T as Object>::get_object_type_name().to_string()),
39        }
40    }
41    #[inline]
42    pub fn new_borrowed<T>(value: &T) -> Instance<I>
43    where
44        T: InterfaceMark<I> + Object + Send + Sync + 'static,
45    {
46        Instance {
47            _interface: std::marker::PhantomData,
48            _target: std::marker::PhantomData,
49            value: AnyBox::new_borrowed(value, <T as Object>::get_object_type_name().to_string()),
50        }
51    }
52}
53
54impl<'a, I> ResolveOwned<'a> for Instance<'a, I>
55where
56    I: ?Sized + Interface,
57{
58    fn resolve_owned(self, ctx: &Context) -> async_graphql::Result<Option<FieldValue<'a>>> {
59        self.value.resolve_owned(ctx)
60    }
61}
62
63pub trait RegisterInstance<I, T>
64where
65    I: ?Sized,
66    T: Object + 'static,
67    T: Send + Sync,
68{
69    #[inline]
70    fn register_instance(registry: Registry) -> Registry {
71        registry
72    }
73}
74
75impl<I, T> Register for Instance<'_, I, T>
76where
77    I: ?Sized,
78    I: Interface + 'static,
79    I: RegisterInstance<I, T>,
80    T: Object + 'static,
81    T: Send + Sync,
82{
83    #[inline]
84    fn register(registry: Registry) -> Registry {
85        let registry = registry.register::<I>();
86        <I as RegisterInstance<I, T>>::register_instance(registry)
87    }
88}
89
90impl<I> Register for Instance<'_, I, ()>
91where
92    I: ?Sized,
93    I: Interface + 'static,
94{
95    #[inline]
96    fn register(registry: Registry) -> Registry {
97        registry.register::<I>()
98    }
99}
100
101impl<I> TypeName for Instance<'_, I>
102where
103    I: Interface + 'static + ?Sized,
104{
105    fn get_type_name() -> Cow<'static, str> {
106        <I as Interface>::get_interface_type_name()
107    }
108}
109
110impl<I> OutputTypeName for Instance<'_, I> where I: Interface + 'static + ?Sized {}