use std::sync::Arc;
use serde_json::Value as JsonValue;
use super::GraphqlError;
use crate::dbs::Session;
use crate::kvs::Datastore;
pub async fn execute_request(
ds: &Arc<Datastore>,
session: &Session,
query: String,
variables: JsonValue,
operation: Option<String>,
) -> Result<JsonValue, GraphqlError> {
let schema = ds.graphql_schema(session).await?;
let mut envelope = serde_json::Map::new();
envelope.insert("query".to_string(), JsonValue::String(query));
if !variables.is_null() {
envelope.insert("variables".to_string(), variables);
}
if let Some(operation) = operation {
envelope.insert("operationName".to_string(), JsonValue::String(operation));
}
let request: async_graphql::Request = serde_json::from_value(JsonValue::Object(envelope))
.map_err(|e| GraphqlError::ResolverError(format!("Invalid GraphQL request: {e}")))?;
let request = request.data(Arc::clone(ds)).data(Arc::new(session.clone()));
let response = schema.execute(request).await;
serde_json::to_value(&response).map_err(|e| {
GraphqlError::InternalError(format!("Failed to serialise GraphQL response: {e}"))
})
}