reactive_graph_graphql_schema/query/behaviours/
entity_behaviour.rs

1use std::sync::Arc;
2
3use async_graphql::Context;
4use async_graphql::Error;
5use async_graphql::Object;
6use async_graphql::Result;
7
8use reactive_graph_behaviour_model_api::EntityBehaviourTypeId;
9use reactive_graph_behaviour_service_api::EntityBehaviourManager;
10use reactive_graph_graph::NamespacedTypeGetter;
11use reactive_graph_type_system_api::EntityTypeManager;
12
13use crate::query::GraphQLBehaviour;
14use crate::query::GraphQLEntityInstance;
15use crate::query::GraphQLEntityType;
16
17pub struct GraphQLEntityBehaviour {
18    entity_behaviour_ty: EntityBehaviourTypeId,
19}
20
21/// An entity behaviour.
22#[Object(name = "EntityBehaviour")]
23impl GraphQLEntityBehaviour {
24    /// The entity type.
25    async fn entity_type(&self, context: &Context<'_>) -> Result<GraphQLEntityType> {
26        let entity_type_manager = context.data::<Arc<dyn EntityTypeManager + Send + Sync>>()?;
27        let entity_type = entity_type_manager
28            .get(&self.entity_behaviour_ty.entity_ty)
29            .ok_or(Error::new(format!("Entity type {} does not exist!", &self.entity_behaviour_ty.entity_ty)))?;
30        Ok(entity_type.into())
31    }
32
33    /// The namespace the behaviour type belongs to.
34    async fn namespace(&self) -> String {
35        self.entity_behaviour_ty.behaviour_ty.namespace()
36    }
37
38    /// The name of the behaviour type.
39    async fn name(&self) -> String {
40        self.entity_behaviour_ty.behaviour_ty.type_name()
41    }
42
43    /// The behaviour type.
44    async fn behaviour(&self) -> GraphQLBehaviour {
45        GraphQLBehaviour::from(self.entity_behaviour_ty.behaviour_ty.clone())
46    }
47
48    /// The instances with the behaviour.
49    async fn instances(&self, context: &Context<'_>) -> Result<Vec<GraphQLEntityInstance>> {
50        let entity_behaviour_manager = context.data::<Arc<dyn EntityBehaviourManager + Send + Sync>>()?;
51        Ok(entity_behaviour_manager
52            .get_instances_by_behaviour(&self.entity_behaviour_ty.behaviour_ty)
53            .into_iter()
54            .map(GraphQLEntityInstance::from)
55            .collect())
56    }
57}
58
59impl From<EntityBehaviourTypeId> for GraphQLEntityBehaviour {
60    fn from(entity_behaviour_ty: EntityBehaviourTypeId) -> Self {
61        GraphQLEntityBehaviour { entity_behaviour_ty }
62    }
63}