dynamic_graphql/
instance.rs

1use std::borrow::Cow;
2
3use async_graphql::dynamic::FieldValue;
4use async_graphql::Context;
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
67    T: Object + 'static,
68    T: Send + Sync,
69{
70    #[inline]
71    fn register_instance(registry: Registry) -> Registry {
72        registry
73    }
74}
75
76impl<I, T> Register for Instance<'_, I, T>
77where
78    I: ?Sized,
79    I: Interface + 'static,
80    I: RegisterInstance<I, T>,
81    T: Object + 'static,
82    T: Send + Sync,
83{
84    #[inline]
85    fn register(registry: Registry) -> Registry {
86        let registry = registry.register::<I>();
87        <I as RegisterInstance<I, T>>::register_instance(registry)
88    }
89}
90
91impl<I> Register for Instance<'_, I, ()>
92where
93    I: ?Sized,
94    I: Interface + 'static,
95{
96    #[inline]
97    fn register(registry: Registry) -> Registry {
98        registry.register::<I>()
99    }
100}
101
102impl<I> TypeName for Instance<'_, I>
103where
104    I: Interface + 'static + ?Sized,
105{
106    fn get_type_name() -> Cow<'static, str> {
107        <I as Interface>::get_interface_type_name()
108    }
109}
110
111impl<I> OutputTypeName for Instance<'_, I> where I: Interface + 'static + ?Sized {}