reactive_graph_graphql_schema/query/instances/
relation_instance.rs

1use std::sync::Arc;
2
3use async_graphql::Context;
4use async_graphql::Object;
5use async_graphql::Result;
6use reactive_graph_behaviour_service_api::RelationBehaviourRegistry;
7use reactive_graph_behaviour_service_api::RelationComponentBehaviourRegistry;
8use reactive_graph_graph::InvalidRelationInstanceError;
9use reactive_graph_reactive_model_impl::ReactiveRelation;
10use reactive_graph_type_system_api::ComponentManager;
11use reactive_graph_type_system_api::RelationTypeManager;
12
13use crate::query::GraphQLComponent;
14use crate::query::GraphQLComponentBehaviour;
15use crate::query::GraphQLEntityInstance;
16use crate::query::GraphQLPropertyInstance;
17use crate::query::GraphQLRelationBehaviour;
18use crate::query::GraphQLRelationType;
19
20pub struct GraphQLRelationInstance {
21    relation_instance: ReactiveRelation,
22}
23
24/// Relation instances are edges from an outbound entity instance to an
25/// inbound entity instance.
26///
27/// The relation instance is of a relation type. The relation type defines
28/// the entity types of the outbound entity instance and the inbound entity
29/// instance. Furthermore, the relation type defines which properties
30/// (name, data type, socket type) a relation instance have to have.
31///
32/// In contrast to the relation type, the relation instance stores values/
33/// documents in its properties.
34#[Object(name = "RelationInstance")]
35impl GraphQLRelationInstance {
36    /// The outbound entity instance.
37    ///
38    /// You can use this in order to navigate from the outbound entity instance to the inbound
39    /// entity instance or vice versa.
40    async fn outbound(&self) -> GraphQLEntityInstance {
41        self.relation_instance.outbound.clone().into()
42    }
43
44    /// The relation type.
45    #[graphql(name = "type")]
46    async fn relation_type(&self, context: &Context<'_>) -> Result<GraphQLRelationType> {
47        let ty = self.relation_instance.relation_type_id();
48        let relation_type_manager = context.data::<Arc<dyn RelationTypeManager + Send + Sync>>()?;
49        let Some(relation_type) = relation_type_manager.get(&ty) else {
50            return Err(InvalidRelationInstanceError::RelationTypeDoesNotExist(ty).into());
51        };
52        Ok(relation_type.into())
53    }
54
55    /// The instance id of the relation instance type.
56    async fn instance_id(&self) -> String {
57        self.relation_instance.ty.instance_id().to_string()
58    }
59
60    /// The inbound entity instance.
61    ///
62    /// You can use this in order to navigate from the inbound entity instance to the outbound
63    /// entity instance or vice versa.
64    async fn inbound(&self) -> GraphQLEntityInstance {
65        self.relation_instance.inbound.clone().into()
66    }
67
68    /// The name of the relation instance.
69    async fn name(&self) -> String {
70        self.relation_instance.name.clone()
71    }
72
73    /// Textual description of the relation instance.
74    async fn description(&self) -> String {
75        self.relation_instance.description.clone()
76    }
77
78    /// The properties of then relation instance.
79    ///
80    /// Each property is represented by its name (String) and it's value. The value is
81    /// a representation of a JSON. Therefore, the value can be boolean, number, string,
82    /// array or an object. For more information about the data types please look at
83    /// https://docs.serde.rs/serde_json/value/enum.Value.html
84    async fn properties(
85        &self,
86        #[graphql(desc = "Filters by property name.")] name: Option<String>,
87        #[graphql(desc = "Filters by property names")] names: Option<Vec<String>>,
88        #[graphql(desc = "If true, the properties are sorted by name")] sort: Option<bool>,
89    ) -> Vec<GraphQLPropertyInstance> {
90        let mut properties: Vec<GraphQLPropertyInstance> = self
91            .relation_instance
92            .properties
93            .iter()
94            .filter(|property_instance| name.is_none() || name.clone().unwrap() == property_instance.key().as_str())
95            .filter(|property_instance| names.is_none() || names.clone().unwrap().contains(property_instance.key()))
96            .map(|property_instance| {
97                GraphQLPropertyInstance::new_relation_property(
98                    self.relation_instance.relation_type_id(),
99                    property_instance.key().clone(),
100                    property_instance.get(),
101                )
102            })
103            .collect();
104        if sort.unwrap_or_default() {
105            properties.sort_by(|a, b| a.name.cmp(&b.name));
106        }
107        properties
108    }
109
110    /// The components which have been actually applied on the relation instance including
111    /// components which have been added after creation.
112    async fn components(&self, context: &Context<'_>) -> Vec<GraphQLComponent> {
113        match context.data::<Arc<dyn ComponentManager + Send + Sync>>() {
114            Ok(component_manager) => self
115                .relation_instance
116                .components
117                .iter()
118                .map(|p| p.key().clone())
119                .filter_map(|component_name| {
120                    component_manager.get(&component_name).map(|component| {
121                        let component: GraphQLComponent = component.into();
122                        component
123                    })
124                })
125                .collect(),
126            Err(_) => Vec::new(),
127        }
128    }
129
130    /// List of relation behaviours which have been actually applied on the relation instance
131    /// including behaviours which have been applied after creation.
132    async fn behaviours(&self, context: &Context<'_>) -> Result<Vec<GraphQLRelationBehaviour>> {
133        let relation_behaviour_registry = context.data::<Arc<dyn RelationBehaviourRegistry + Send + Sync>>()?;
134        Ok(self
135            .relation_instance
136            .behaviours
137            .iter()
138            .filter_map(move |p| {
139                let behaviour_ty = p.key();
140                relation_behaviour_registry
141                    .get_by_behaviour_type(behaviour_ty)
142                    .map(GraphQLRelationBehaviour::from)
143            })
144            .collect())
145    }
146
147    /// List of component behaviours which have been actually applied on the entity instance
148    /// including behaviours which have been applied after creation.
149    async fn component_behaviours(&self, context: &Context<'_>) -> Result<Vec<GraphQLComponentBehaviour>> {
150        let relation_component_behaviour_registry = context.data::<Arc<dyn RelationComponentBehaviourRegistry + Send + Sync>>()?;
151        Ok(self
152            .relation_instance
153            .behaviours
154            .iter()
155            .filter_map(move |p| {
156                let behaviour_ty = p.key();
157                relation_component_behaviour_registry
158                    .get_by_behaviour_type(behaviour_ty)
159                    .map(GraphQLComponentBehaviour::from)
160            })
161            .collect())
162    }
163}
164
165impl From<ReactiveRelation> for GraphQLRelationInstance {
166    fn from(relation_instance: ReactiveRelation) -> Self {
167        GraphQLRelationInstance { relation_instance }
168    }
169}