1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
//! This module provides the Warpgrapher client. use super::error::{Error, ErrorKind}; use actix_web::client::Client; use inflector::Inflector; use log::{debug, trace}; use serde_json::{json, Value}; use std::collections::BTreeMap; /// Takes and executes a raw GraphQL query. Takes an optional input which is inserted /// in the GraphQL request as "input" in the variables. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use std::env::var_os; /// use warpgrapher::client::graphql; /// /// let query = "query { Project { id name } }"; /// let results = graphql("http://localhost:5000/graphql".to_owned(), query.to_owned(), None); /// let projects = results.unwrap().get("Project"); /// ``` #[actix_rt::main] pub async fn graphql( endpoint: String, query: String, input: Option<Value>, ) -> Result<Value, Error> { // TODO: return a Future let req_body = json!({ "query": query.to_string(), "variables": { "input": input } }); let mut res = Client::default() .post(endpoint) .header("Content-Type", "application/json") .send_json(&req_body) .await .map_err(|e| Error::new(ErrorKind::ClientRequestFailed(format!("{:#?}", e)), None))?; let body: Value = res .json() .await .map_err(|_e| Error::new(ErrorKind::ClientReceivedInvalidJson, None))?; trace!("Response Body: {:#?}", body); match body.get("data") { None => Err(Error::new( ErrorKind::ClientRequestUnexpectedPayload(body.to_owned()), None, )), Some(data) => { debug!("Result Data: {:#?}", data); Ok(data.to_owned()) } } } /// A Warpgrapher GraphQL client /// /// The [`WarpgrapherClient`] provides a set of CRUD operations that will /// automatically generate GraphQL queries that conform to the wargrapher API /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// ``` pub struct WarpgrapherClient { endpoint: String, } impl WarpgrapherClient { /// Takes an endpoint string and creates a new [`WarpgrapherClient`]. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// ``` pub fn new(endpoint: &str) -> WarpgrapherClient { WarpgrapherClient { endpoint: endpoint.to_string(), } } /// Takes the name of a WarpgrapherType and executes a NodeCreate operation. Requires /// a query shape and the input of the node being created. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// /// let projects = client.create_node( /// "Project", /// "id name description", /// &json!({"name": "TodoApp", "description": "TODO list tracking application"}), /// ); /// ``` pub fn create_node( &mut self, type_name: &str, shape: &str, input: &Value, ) -> Result<Value, Error> { let query = self.fmt_create_node_query(type_name, shape); debug!( "WarpGrapherClient create_node -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, Some(input.to_owned()))?; self.strip(&result, &format!("{}Create", type_name)) } /// Takes the name of a WarpgrapherType and a relationship property on that /// types and executes a RelCreate operation. Requires also a query shape, /// an input to match the source node(s) for which the rel(s) will be created, /// and an input of the relationship being created. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http:://localhost:5000/graphql"); /// /// let proj_issues = client.create_rel( /// "Project", /// "issues", /// "id props { since } src { id name } dst { id name }", /// &json!({"name": "ProjectName"}), /// &json!({"props": {"since": "2000"}, /// "dst": {"Feature": {"NEW": {"name": "NewFeature"}}}}) /// ); /// ``` pub fn create_rel( &mut self, type_name: &str, rel_name: &str, shape: &str, match_input: &Value, create_input: &Value, ) -> Result<Value, Error> { let query = self.fmt_create_rel_query(type_name, rel_name, shape); let input = json!({"match": match_input, "create": create_input}); debug!( "WarpGrapherClient create_rel -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, Some(input))?; self.strip( &result, &format!("{}{}Create", type_name, rel_name.to_title_case()), ) } /// Takes the name of a WarpgrapherType and executes a Delete operation. /// Takes two optional inputs. The first selects the node(s) for deletion. /// The second contains options for forcing the delete, meaning deleting /// node along with any relationships to and from it -- without the force flag, /// deleting a node with relationships will fail. Also contains options for /// deleting additional nodes and rels connected to the target node. Returns /// the number of nodes of the WarpgrapherType deleted. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// use serde_json::json; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// /// let projects = client.delete_node( /// "Project", /// Some(&json!({"name": "MJOLNIR"})), /// None); /// ``` pub fn delete_node( &mut self, type_name: &str, match_input: Option<&Value>, delete_input: Option<&Value>, ) -> Result<Value, Error> { let query = self.fmt_delete_node_query(type_name); let input = json!({"match": match_input, "delete": delete_input}); debug!( "WarpGrapherClient delete_node -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, Some(input))?; self.strip(&result, &(type_name.to_string() + "Delete")) } /// Takes the name of a WarpgrapherType and a relationship property on that /// types and executes a RelDelete operation. Takes three optional inputs. The /// first selects the relationship(s) for deletion. The second and third, /// if present, request the deletion of the src and dst nodes associated with the /// relationship, and potentially additional nodes and rels as well. Returns /// the number of matched relationships deleted. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http:://localhost:5000/graphql"); /// /// let proj_issues = client.delete_rel("Project", "issues", /// Some(&json!({"props": {"since": "2000"}})), /// None, /// Some(&json!({"Bug": {"force": true}})) /// ); /// ``` pub fn delete_rel( &mut self, type_name: &str, rel_name: &str, match_input: Option<&Value>, src_input: Option<&Value>, dst_input: Option<&Value>, ) -> Result<Value, Error> { let query = self.fmt_delete_rel_query(type_name, rel_name); let mut m = BTreeMap::new(); if let Some(mi) = match_input { m.insert("match".to_owned(), mi); } if let Some(src) = src_input { m.insert("src".to_owned(), src); } if let Some(dst) = dst_input { m.insert("dst".to_owned(), dst); } let input = if m.is_empty() { None } else { Some(json!(m)) }; debug!( "WarpGrapherClient delete_rel -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, input)?; self.strip( &result, &format!("{}{}Delete", type_name, rel_name.to_title_case()), ) } /// Takes the name of a WarpgrapherType and executes a Read operation. Requires /// a query shape and takes an optional input which filters the results. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// /// let projects = client.read_node("Project", "id name description", None); /// ``` pub fn read_node( &mut self, type_name: &str, shape: &str, input: Option<&Value>, ) -> Result<Value, Error> { let query = self.fmt_read_node_query(type_name, shape); debug!( "WarpGrapherClient read_node -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, input.cloned())?; self.strip(&result, type_name) } /// Takes the name of a WarpgrapherType and a relationship property on that /// types and executes a read operation. Also takes an option input with match /// criteria for selecting the relationship to read. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http:://localhost:5000/graphql"); /// /// let proj_issues = client.read_rel("Project", "issues", /// "id props { since }", /// Some(&json!({"props": {"since": "2000"}})) /// ); /// ``` pub fn read_rel( &mut self, type_name: &str, rel_name: &str, shape: &str, input: Option<&Value>, ) -> Result<Value, Error> { let query = self.fmt_read_rel_query(type_name, rel_name, shape); debug!( "WarpGrapherClient read_rel -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, input.cloned())?; self.strip( &result, &format!("{}{}", type_name, rel_name.to_title_case()), ) } /// Takes the name of a WarpgrapherType and executes an Update operation. /// Requires a query shape, an optional match component of the input, and a /// mandatory update component of the input. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http://localhost:5000/graphql"); /// /// let projects = client.update_node( /// "Project", /// "id name status", /// Some(&json!({"name": "TodoApp"})), /// &json!({"status": "ACTIVE"}), /// ); /// ``` pub fn update_node( &mut self, type_name: &str, shape: &str, match_input: Option<&Value>, update_input: &Value, ) -> Result<Value, Error> { let query = self.fmt_update_node_query(type_name, shape); let input = json!({"match": match_input, "modify": update_input}); debug!( "WarpGrapherClient update_node -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, Some(input))?; self.strip(&result, &format!("{}Update", type_name)) } /// Takes the name of a WarpgrapherType and a relationship property on that /// types and executes a RelUpdate operation. Requires a shape of result to /// be returned. Takes an optional input that selects the relationship for /// update, and a mandatory input describing the update to be performed. /// Returns the number of matched relationships deleted. /// /// [`WarpgrapherClient`]: ./struct.WarpgrapherClient.html /// /// # Examples /// /// ```rust,no_run /// use serde_json::json; /// use std::env::var_os; /// use warpgrapher::WarpgrapherClient; /// /// let mut client = WarpgrapherClient::new("http:://localhost:5000/graphql"); /// /// let proj_issues = client.update_rel("Project", "issues", /// "id props {since} src {id name} dst {id name}", /// Some(&json!({"props": {"since": "2000"}})), /// &json!({"props": {"since": "2010"}}) /// ); /// ``` pub fn update_rel( &mut self, type_name: &str, rel_name: &str, shape: &str, match_input: Option<&Value>, update_input: &Value, ) -> Result<Value, Error> { let query = self.fmt_update_rel_query(type_name, rel_name, shape); let input = json!({"match": match_input, "update": update_input}); debug!( "WarpGrapherClient update_rel -- query: {:#?}, input: {:#?}", query, input ); let result = graphql(self.endpoint.to_owned(), query, Some(input))?; self.strip( &result, &format!("{}{}Update", type_name, rel_name.to_title_case()), ) } fn fmt_create_node_query(&self, type_name: &str, shape: &str) -> String { format!( "mutation Create($input: {type_name}CreateMutationInput!) {{ {type_name}Create(input: $input) {{ {shape} }} }}", type_name = type_name, shape = shape ) } fn fmt_create_rel_query(&self, type_name: &str, rel_name: &str, shape: &str) -> String { format!( "mutation Create($input: {type_name}{rel_name}CreateInput!) {{ {type_name}{rel_name}Create(input: $input) {{ {shape} }} }}", type_name = type_name, rel_name = rel_name.to_title_case(), shape = shape ) } fn fmt_delete_node_query(&self, type_name: &str) -> String { format!( "mutation Delete($input: {type_name}DeleteInput!) {{ {type_name}Delete(input: $input) }}", type_name = type_name ) } fn fmt_delete_rel_query(&self, type_name: &str, rel_name: &str) -> String { format!( "mutation Delete($input: {type_name}{rel_name}DeleteInput!) {{ {type_name}{rel_name}Delete(input: $input) }}", type_name = type_name, rel_name = rel_name.to_title_case(), ) } fn fmt_read_node_query(&self, type_name: &str, shape: &str) -> String { format!( "query Read($input: {type_name}QueryInput) {{ {type_name}(input: $input) {{ {shape} }} }}", type_name = type_name, shape = shape ) } fn fmt_read_rel_query(&self, type_name: &str, rel_name: &str, shape: &str) -> String { format!( "query Read($input: {type_name}{rel_name}QueryInput) {{ {type_name}{rel_name}(input: $input) {{ {shape} }} }}", type_name = type_name, rel_name = rel_name.to_title_case(), shape = shape ) } fn fmt_update_node_query(&self, type_name: &str, shape: &str) -> String { format!( "mutation Update($input: {type_name}UpdateInput!) {{ {type_name}Update(input: $input) {{ {shape} }} }}", type_name = type_name, shape = shape ) } fn fmt_update_rel_query(&self, type_name: &str, rel_name: &str, shape: &str) -> String { format!( "mutation Update($input: {type_name}{rel_name}UpdateInput!) {{ {type_name}{rel_name}Update(input: $input) {{ {shape} }} }}", type_name = type_name, rel_name = rel_name.to_title_case(), shape = shape ) } fn strip(&self, data: &Value, name: &str) -> Result<Value, Error> { match data.get(name) { None => Err(Error::new( ErrorKind::ClientRequestUnexpectedPayload(data.to_owned()), None, )), Some(v) => Ok(v.to_owned()), } } } #[cfg(test)] mod tests { use super::WarpgrapherClient; #[test] fn new() { let endpoint = "http://localhost:5000/graphql"; let client = WarpgrapherClient::new(&endpoint); assert_eq!(client.endpoint, endpoint); } #[test] fn fmt_read_node_query() { let endpoint = "http://localhost:5000/graphql"; let client = WarpgrapherClient::new(&endpoint); let actual = client.fmt_read_node_query("Project", "id"); let expected = r#"query Read($input: ProjectQueryInput) { Project(input: $input) { id } }"#; assert_eq!(actual, expected); } #[test] fn fmt_create_node_query() { let endpoint = "http://localhost:5000/graphql"; let client = WarpgrapherClient::new(&endpoint); let actual = client.fmt_create_node_query("Project", "id"); let expected = r#"mutation Create($input: ProjectCreateMutationInput!) { ProjectCreate(input: $input) { id } }"#; assert_eq!(actual, expected); } }