Parse a graph traversal response into a SubGraph.
(
resp: &nodedb_types::protocol::NativeResponse,
)
| 49 | |
| 50 | /// Parse a graph traversal response into a SubGraph. |
| 51 | pub(crate) fn parse_subgraph_response( |
| 52 | resp: &nodedb_types::protocol::NativeResponse, |
| 53 | ) -> NodeDbResult<SubGraph> { |
| 54 | let rows = match &resp.rows { |
| 55 | Some(r) => r, |
| 56 | None => return Ok(SubGraph::empty()), |
| 57 | }; |
| 58 | |
| 59 | let mut nodes = Vec::new(); |
| 60 | let mut edges = Vec::new(); |
| 61 | |
| 62 | for row in rows { |
| 63 | let text = match row.first().and_then(|v| v.as_str()) { |
| 64 | Some(t) => t, |
| 65 | None => continue, |
| 66 | }; |
| 67 | |
| 68 | if let Ok(val) = sonic_rs::from_str::<serde_json::Value>(text) { |
| 69 | if let Some(obj) = val.as_object() { |
| 70 | if let Some(ns) = obj.get("nodes").and_then(|v| v.as_array()) { |
| 71 | for n in ns { |
| 72 | if let Some(id) = n.get("id").and_then(|v| v.as_str()) { |
| 73 | let depth = n.get("depth").and_then(|v| v.as_u64()).unwrap_or(0) as u8; |
| 74 | nodes.push(SubGraphNode { |
| 75 | id: NodeId::from_validated(id.to_owned()), |
| 76 | depth, |
| 77 | properties: HashMap::new(), |
| 78 | }); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | if let Some(es) = obj.get("edges").and_then(|v| v.as_array()) { |
| 83 | for e in es { |
| 84 | let from = e |
| 85 | .get("from") |
| 86 | .or_else(|| e.get("src")) |
| 87 | .and_then(|v| v.as_str()) |
| 88 | .unwrap_or(""); |
| 89 | let to = e |
| 90 | .get("to") |
| 91 | .or_else(|| e.get("dst")) |
| 92 | .and_then(|v| v.as_str()) |
| 93 | .unwrap_or(""); |
| 94 | let label = e.get("label").and_then(|v| v.as_str()).unwrap_or(""); |
| 95 | edges.push(SubGraphEdge { |
| 96 | id: EdgeId::try_first( |
| 97 | NodeId::from_validated(from.to_owned()), |
| 98 | NodeId::from_validated(to.to_owned()), |
| 99 | label, |
| 100 | ) |
| 101 | .expect("server wire label already validated"), |
| 102 | from: NodeId::from_validated(from.to_owned()), |
| 103 | to: NodeId::from_validated(to.to_owned()), |
| 104 | label: label.to_string(), |
| 105 | properties: HashMap::new(), |
| 106 | }); |
| 107 | } |
| 108 | } |