reactive_graph_std_array/behaviour/entity/
get_by_index.rs

1use 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 uuid::Uuid;
8
9use reactive_graph_std_array_model::ArrayGetByIndexProperties::ARRAY;
10use reactive_graph_std_array_model::ArrayGetByIndexProperties::INDEX;
11use reactive_graph_std_result_model::ResultArrayProperties::RESULT;
12
13entity_behaviour!(
14    ArrayGetByIndex,
15    ArrayGetByIndexFactory,
16    ArrayGetByIndexFsm,
17    ArrayGetByIndexBehaviourTransitions,
18    ArrayGetByIndexValidator
19);
20
21behaviour_validator!(ArrayGetByIndexValidator, Uuid, ReactiveEntity, ARRAY.as_ref(), RESULT.as_ref(), INDEX.as_ref());
22
23impl BehaviourInit<Uuid, ReactiveEntity> for ArrayGetByIndexBehaviourTransitions {
24    fn init(&self) -> Result<(), BehaviourInitializationFailed> {
25        if let Some(array) = self.reactive_instance.get(ARRAY) {
26            if let Some(index) = self.reactive_instance.get(INDEX) {
27                if let Some(result) = get_by_index(&array, &index) {
28                    self.reactive_instance.set(RESULT, result);
29                }
30            }
31        }
32        Ok(())
33    }
34}
35
36impl BehaviourConnect<Uuid, ReactiveEntity> for ArrayGetByIndexBehaviourTransitions {
37    fn connect(&self) -> Result<(), BehaviourConnectFailed> {
38        let reactive_instance = self.reactive_instance.clone();
39        self.property_observers.observe_with_handle(ARRAY.as_ref(), move |array: &Value| {
40            if let Some(index) = reactive_instance.get(INDEX) {
41                if let Some(result) = get_by_index(array, &index) {
42                    reactive_instance.set(RESULT, result);
43                }
44            }
45        });
46        let reactive_instance = self.reactive_instance.clone();
47        self.property_observers.observe_with_handle(INDEX.as_ref(), move |index: &Value| {
48            if let Some(array) = reactive_instance.get(ARRAY) {
49                if let Some(result) = get_by_index(&array, index) {
50                    reactive_instance.set(RESULT, result);
51                }
52            }
53        });
54        Ok(())
55    }
56}
57
58impl BehaviourShutdown<Uuid, ReactiveEntity> for ArrayGetByIndexBehaviourTransitions {}
59impl BehaviourTransitions<Uuid, ReactiveEntity> for ArrayGetByIndexBehaviourTransitions {}
60
61fn get_by_index(array: &Value, index: &Value) -> Option<Value> {
62    match index.as_u64() {
63        Some(index) => match array.as_array() {
64            Some(array) => array.get(index as usize).cloned(),
65            None => None,
66        },
67        _ => None,
68    }
69}