routee_compass/app/compass/
compass_json_extensions.rs

1use super::compass_input_field::CompassInputField;
2use crate::app::compass::CompassAppError;
3
4pub trait CompassJsonExtensions {
5    fn get_queries(&self) -> Result<Vec<serde_json::Value>, CompassAppError>;
6}
7
8impl CompassJsonExtensions for serde_json::Value {
9    /// attempts to read queries from the user in the three following ways:
10    ///   1. top-level of JSON is an array -> return it directly
11    ///   2. top-level of JSON is object without a "queries" field -> wrap it in an array and return it
12    ///   3. top-level of JSON is object with a "queries" field ->  if the value at "queries" is an array, return it
13    fn get_queries(&self) -> Result<Vec<serde_json::Value>, CompassAppError> {
14        match self {
15            serde_json::Value::Array(queries) => Ok(queries.to_owned()),
16            serde_json::Value::Object(obj) => match obj.get(CompassInputField::Queries.to_str()) {
17                None => Ok(vec![self.to_owned()]),
18                Some(value) => match value {
19                    serde_json::Value::Array(vec) => Ok(vec.to_owned()),
20                    _ => {
21                        let msg = String::from("user JSON argument must be an object or an array");
22                        Err(CompassAppError::CompassFailure(msg))
23                    }
24                },
25            },
26            _ => Err(CompassAppError::CompassFailure(String::from(
27                "expected object, object with queries, or array input",
28            ))),
29        }
30    }
31}