x-rs 0.1.0

x private library
Documentation
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use crate::error::{Error, Result};

const BUNDLED_OPERATIONS: &str = include_str!("../operations.json");

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Operation {
    #[serde(rename = "queryId")]
    pub query_id: String,
    pub method: String,
}

#[derive(Debug, Clone)]
pub struct Operations {
    ops: HashMap<String, Operation>,
}

impl Operations {
    pub fn new() -> Result<Self> {
        let json: Value = serde_json::from_str(BUNDLED_OPERATIONS)?;
        let ops = Self::parse_operations(&json);
        Ok(Self { ops })
    }

    pub async fn get(&self, name: &str) -> Result<Operation> {
        self.ops
            .get(name)
            .cloned()
            .ok_or_else(|| Error::OperationNotFound(name.into()))
    }

    fn parse_operations(json: &Value) -> HashMap<String, Operation> {
        let mut ops = HashMap::new();

        if let Some(obj) = json.as_object() {
            for (name, value) in obj {
                let query_id = value
                    .get("queryId")
                    .and_then(|v| v.as_str())
                    .map(Into::into);

                let method = value
                    .get("method")
                    .and_then(|v| v.as_str())
                    .unwrap_or("GET")
                    .into();

                if let Some(query_id) = query_id {
                    ops.insert(name.clone(), Operation { query_id, method });
                }
            }
        }

        ops
    }
}