reactive_graph_graphql_schema/query/instances/
entity_instance.rs

1use std::sync::Arc;
2
3use async_graphql::Context;
4use async_graphql::Object;
5use async_graphql::Result;
6use uuid::Uuid;
7
8use reactive_graph_behaviour_service_api::EntityBehaviourRegistry;
9use reactive_graph_behaviour_service_api::EntityComponentBehaviourRegistry;
10use reactive_graph_graph::InvalidEntityInstanceError;
11use reactive_graph_graph::RelationTypeId;
12use reactive_graph_reactive_model_impl::ReactiveEntity;
13use reactive_graph_reactive_service_api::ReactiveRelationManager;
14use reactive_graph_type_system_api::ComponentManager;
15use reactive_graph_type_system_api::EntityTypeManager;
16
17use crate::query::GraphQLComponent;
18use crate::query::GraphQLComponentBehaviour;
19use crate::query::GraphQLEntityBehaviour;
20use crate::query::GraphQLEntityType;
21use crate::query::GraphQLPropertyInstance;
22use crate::query::GraphQLRelationInstance;
23use crate::validator::NamespacedTypeValidator;
24
25pub struct GraphQLEntityInstance {
26    entity_instance: ReactiveEntity,
27}
28
29/// Entity instances represents an typed objects which contains properties.
30///
31/// The entity type defines the properties (name, data type and socket type).
32///
33/// In contrast to the entity type the entity instance stores values in it's
34/// properties.
35#[Object(name = "EntityInstance")]
36impl GraphQLEntityInstance {
37    /// The entity type of the entity instance.
38    #[graphql(name = "type")]
39    async fn entity_type(&self, context: &Context<'_>) -> Result<GraphQLEntityType> {
40        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
41        let Some(entity_type) = entity_type_manager.get(&self.entity_instance.ty) else {
42            return Err(InvalidEntityInstanceError::EntityTypeDoesNotExist(self.entity_instance.ty.clone()).into());
43        };
44        Ok(entity_type.into())
45    }
46
47    /// The unique identifier of the entity instance.
48    async fn id(&self) -> Uuid {
49        self.entity_instance.id
50    }
51
52    /// The label of the entity instance if available.
53    async fn label(&self) -> Option<String> {
54        self.entity_instance
55            .properties
56            .get("label")
57            .and_then(|property_instance| property_instance.as_string())
58    }
59
60    /// The name of the entity instance.
61    async fn name(&self) -> String {
62        self.entity_instance.name.clone()
63    }
64
65    /// Textual description of the entity instance.
66    async fn description(&self) -> String {
67        self.entity_instance.description.clone()
68    }
69
70    /// The properties of then entity instance.
71    ///
72    /// Each property is represented by it's name (String) and it's value. The value is
73    /// a representation of a JSON. Therefore the value can be boolean, number, string,
74    /// array or an object. For more information about the data types please look at
75    /// https://docs.serde.rs/serde_json/value/enum.Value.html
76    async fn properties(
77        &self,
78        #[graphql(desc = "Filters by property name")] name: Option<String>,
79        #[graphql(desc = "Filters by property names")] names: Option<Vec<String>>,
80        #[graphql(desc = "If true, the properties are sorted by name")] sort: Option<bool>,
81    ) -> Vec<GraphQLPropertyInstance> {
82        let mut properties: Vec<GraphQLPropertyInstance> = self
83            .entity_instance
84            .properties
85            .iter()
86            .filter(|property_instance| name.is_none() || name.clone().unwrap().as_str() == property_instance.key().as_str())
87            .filter(|property_instance| names.is_none() || names.clone().unwrap().contains(property_instance.key()))
88            .map(|property_instance| {
89                GraphQLPropertyInstance::new_entity_property(self.entity_instance.ty.clone(), property_instance.key().clone(), property_instance.get())
90            })
91            .collect();
92        if sort.unwrap_or_default() {
93            properties.sort_by(|a, b| a.name.cmp(&b.name));
94        }
95        properties
96    }
97
98    /// The components which have been actually applied on the entity instance including
99    /// components which have been added after creation.
100    async fn components(&self, context: &Context<'_>) -> Vec<GraphQLComponent> {
101        match context.data::<Arc<dyn ComponentManager + Send + Sync>>() {
102            Ok(component_manager) => self
103                .entity_instance
104                .components
105                .iter()
106                .map(|p| p.key().clone())
107                .filter_map(|component_ty| {
108                    component_manager.get(&component_ty).map(|component| {
109                        let component: GraphQLComponent = component.into();
110                        component
111                    })
112                })
113                .collect(),
114            Err(_) => Vec::new(),
115        }
116    }
117
118    /// List of entity behaviours which have been actually applied on the entity instance
119    /// including behaviours which have been applied after creation.
120    async fn behaviours(&self, context: &Context<'_>) -> Result<Vec<GraphQLEntityBehaviour>> {
121        let entity_behaviour_registry = context.data::<Arc<dyn EntityBehaviourRegistry + Send + Sync>>()?;
122        Ok(self
123            .entity_instance
124            .behaviours
125            .iter()
126            .filter_map(move |p| {
127                let behaviour_ty = p.key();
128                entity_behaviour_registry.get_by_behaviour_type(behaviour_ty).map(GraphQLEntityBehaviour::from)
129            })
130            .collect())
131    }
132
133    /// List of component behaviours which have been actually applied on the entity instance
134    /// including behaviours which have been applied after creation.
135    async fn component_behaviours(&self, context: &Context<'_>) -> Result<Vec<GraphQLComponentBehaviour>> {
136        let entity_component_behaviour_registry = context.data::<Arc<dyn EntityComponentBehaviourRegistry + Send + Sync>>()?;
137        Ok(self
138            .entity_instance
139            .behaviours
140            .iter()
141            .filter_map(move |p| {
142                let behaviour_ty = p.key();
143                entity_component_behaviour_registry
144                    .get_by_behaviour_type(behaviour_ty)
145                    .map(GraphQLComponentBehaviour::from)
146            })
147            .collect())
148    }
149
150    /// List of relation instances which starts at this entity instance.
151    async fn outbound(
152        &self,
153        context: &Context<'_>,
154        #[graphql(
155            name = "type",
156            desc = "The fully qualified namespace of the outbound relation type.",
157            validator(custom = "NamespacedTypeValidator::new()")
158        )]
159        outbound_type: Option<String>,
160    ) -> Result<Vec<GraphQLRelationInstance>> {
161        let relation_instance_manager = context.data::<Arc<dyn ReactiveRelationManager + Send + Sync>>()?;
162        let outbound_ty = RelationTypeId::parse_optional_namespace(outbound_type)?;
163        let relation_instances = relation_instance_manager
164            .get_by_outbound_entity(self.entity_instance.id)
165            .iter()
166            .filter(|relation_instance| match &outbound_ty {
167                Some(outbound_ty) => outbound_ty == &relation_instance.relation_type_id(),
168                None => true,
169            })
170            .map(|relation_instance| relation_instance.clone().into())
171            .collect();
172        Ok(relation_instances)
173    }
174
175    /// List of relation instances which ends at this entity instance.
176    async fn inbound(
177        &self,
178        context: &Context<'_>,
179        #[graphql(
180            name = "type",
181            desc = "The fully qualified namespace of the inbound relation type",
182            validator(custom = "NamespacedTypeValidator::new()")
183        )]
184        inbound_type: Option<String>,
185    ) -> Result<Vec<GraphQLRelationInstance>> {
186        let relation_instance_manager = context.data::<Arc<dyn ReactiveRelationManager + Send + Sync>>()?;
187        let inbound_ty = RelationTypeId::parse_optional_namespace(inbound_type)?;
188        let relation_instances = relation_instance_manager
189            .get_by_inbound_entity(self.entity_instance.id)
190            .iter()
191            .filter(|relation_instance| match &inbound_ty {
192                Some(inbound_ty) => inbound_ty == &relation_instance.relation_type_id(),
193                None => true,
194            })
195            .map(|relation_instance| relation_instance.clone().into())
196            .collect();
197        Ok(relation_instances)
198    }
199}
200
201impl From<ReactiveEntity> for GraphQLEntityInstance {
202    fn from(entity_instance: ReactiveEntity) -> Self {
203        GraphQLEntityInstance { entity_instance }
204    }
205}