reactive_graph_std_array/behaviour/entity/
push.rs1use reactive_graph_behaviour_model_api::behaviour_validator;
2use reactive_graph_behaviour_model_api::prelude::*;
3use reactive_graph_behaviour_model_impl::entity_behaviour;
4use reactive_graph_graph::prelude::*;
5use reactive_graph_reactive_model_impl::ReactiveEntity;
6use serde_json::Value;
7use serde_json::json;
8use uuid::Uuid;
9
10use reactive_graph_std_array_model::ArrayPushProperties::ARRAY;
11use reactive_graph_std_array_model::ArrayPushProperties::VALUE;
12use reactive_graph_std_result_model::ResultArrayProperties::RESULT;
13
14entity_behaviour!(ArrayPush, ArrayPushFactory, ArrayPushFsm, ArrayPushBehaviourTransitions, ArrayPushValidator);
15
16behaviour_validator!(ArrayPushValidator, Uuid, ReactiveEntity, ARRAY.as_ref(), RESULT.as_ref(), VALUE.as_ref());
17
18impl BehaviourInit<Uuid, ReactiveEntity> for ArrayPushBehaviourTransitions {
19 fn init(&self) -> Result<(), BehaviourInitializationFailed> {
20 if let Some(array) = self.reactive_instance.get(ARRAY) {
21 if let Some(value) = self.reactive_instance.get(VALUE) {
22 self.reactive_instance.set(RESULT, push_array(&array, value));
23 }
24 }
25 Ok(())
26 }
27}
28
29impl BehaviourConnect<Uuid, ReactiveEntity> for ArrayPushBehaviourTransitions {
30 fn connect(&self) -> Result<(), BehaviourConnectFailed> {
31 let reactive_instance = self.reactive_instance.clone();
32 self.property_observers.observe_with_handle(ARRAY.as_ref(), move |array: &Value| {
33 if let Some(value) = reactive_instance.get(VALUE) {
34 reactive_instance.set(RESULT, push_array(array, value));
35 }
36 });
37 let reactive_instance = self.reactive_instance.clone();
38 self.property_observers.observe_with_handle(VALUE.as_ref(), move |value: &Value| {
39 if let Some(array) = reactive_instance.get(ARRAY) {
40 reactive_instance.set(RESULT, push_array(&array, value.clone()));
41 }
42 });
43 Ok(())
44 }
45}
46
47impl BehaviourShutdown<Uuid, ReactiveEntity> for ArrayPushBehaviourTransitions {}
48impl BehaviourTransitions<Uuid, ReactiveEntity> for ArrayPushBehaviourTransitions {}
49
50fn push_array(array: &Value, value: Value) -> Value {
51 match array.as_array() {
52 Some(array) => {
53 let mut array = array.clone();
54 array.push(value);
55 Value::Array(array)
56 }
57 None => json!([value]),
58 }
59}