reactive_graph_runtime_graphql_schema/mutation/
command.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_graphql::Context;
5use async_graphql::Error;
6use async_graphql::Object;
7use async_graphql::Result;
8use async_graphql::Value;
9
10use reactive_graph_command_api::CommandManager;
11use reactive_graph_command_model::reactive_graph::command::command::CommandProperties;
12
13use crate::properties::GraphQLCommandResult;
14
15#[derive(Default)]
16pub struct MutationCommands;
17
18/// Mutations for plugins.
19#[Object]
20impl MutationCommands {
21    async fn execute(&self, context: &Context<'_>, name: String, args: Option<HashMap<String, Value>>) -> Result<Option<GraphQLCommandResult>> {
22        let command_manager = context.data::<Arc<dyn CommandManager + Send + Sync>>()?;
23        let command = command_manager.get_command(&name).map_err(|_| Error::new("No such command"))?;
24        let convert_result = convert_result();
25        let result = match args.map(convert_args) {
26            Some(args) => command.execute_with_args(args),
27            None => command.execute(),
28        }
29        .map_err(|_| Error::new("Command execution failed"))?
30        .map(convert_result);
31        Ok(result)
32    }
33}
34
35fn convert_args(args: HashMap<String, Value>) -> HashMap<String, serde_json::Value> {
36    args.into_iter().filter_map(map_entry).collect()
37}
38
39fn map_entry(entry: (String, Value)) -> Option<(String, serde_json::Value)> {
40    match entry.1.into_json() {
41        Ok(v) => Some((entry.0, v)),
42        Err(_) => None,
43    }
44}
45
46fn convert_result() -> impl FnOnce(serde_json::Value) -> GraphQLCommandResult {
47    |result: serde_json::Value| GraphQLCommandResult::new(CommandProperties::CMD_RESULT.to_string(), result)
48}