reactive_graph_dynamic_graph_impl/field/entity/
query.rs1use crate::field::property::field_arguments::add_entity_type_properties_as_field_arguments;
2use crate::field::property::filter::get_entity_instances_by_type_filter_by_properties;
3use crate::object::types::DynamicGraphTypeDefinition;
4use async_graphql::Error;
5use async_graphql::dynamic::Field;
6use async_graphql::dynamic::FieldFuture;
7use async_graphql::dynamic::FieldValue;
8use async_graphql::dynamic::InputValue;
9use async_graphql::dynamic::TypeRef;
10use reactive_graph_graph::EntityType;
11use reactive_graph_reactive_service_api::ReactiveEntityManager;
12use std::str::FromStr;
13use std::sync::Arc;
14use uuid::Uuid;
15
16pub fn entity_query_field(entity_type: &EntityType) -> Field {
17 let ty = entity_type.ty.clone();
18 let entity_type_inner = entity_type.clone();
19 let dy_ty = DynamicGraphTypeDefinition::from(&ty);
20 let mut field = Field::new(dy_ty.field_name(), TypeRef::named_nn_list_nn(dy_ty.to_string()), move |ctx| {
21 let ty = ty.clone();
22 let entity_type = entity_type_inner.clone();
23 FieldFuture::new(async move {
24 let entity_instance_manager = ctx.data::<Arc<dyn ReactiveEntityManager + Send + Sync>>()?;
25 if let Ok(id) = ctx.args.try_get("id") {
26 let id = Uuid::from_str(id.string()?)?;
27 let entity_instance = entity_instance_manager.get(id).ok_or(Error::new("Uuid not found"))?;
28 if entity_instance.ty != ty {
29 return Err(Error::new(format!("Entity {} is not a {}", id, &ty)));
30 }
31 return Ok(Some(FieldValue::list(vec![FieldValue::owned_any(entity_instance)])));
32 }
33 if let Ok(label) = ctx.args.try_get("label") {
34 let entity_instance = entity_instance_manager.get_by_label(label.string()?).ok_or(Error::new("Label not found"))?;
35 if entity_instance.ty != ty {
36 return Err(Error::new(format!("Entity {} is not a {}", entity_instance.id, &ty)));
37 }
38 return Ok(Some(FieldValue::list(vec![FieldValue::owned_any(entity_instance)])));
39 }
40 let instances = get_entity_instances_by_type_filter_by_properties(&ctx, &entity_type, entity_instance_manager);
41 Ok(Some(FieldValue::list(instances.into_iter().map(FieldValue::owned_any))))
42 })
43 })
44 .description(entity_type.description.clone())
45 .argument(InputValue::new("id", TypeRef::named(TypeRef::STRING)))
46 .argument(InputValue::new("label", TypeRef::named(TypeRef::STRING)));
47 field = add_entity_type_properties_as_field_arguments(field, entity_type, true, true);
48 field
49}