Skip to main content

vecgraph_proto/traits/
node_traits.rs

1use crate::{Node, NodeWithVector};
2use vecgraph_core::VecGraphError;
3
4impl TryFrom<Node> for vecgraph_core::Node {
5    type Error = VecGraphError;
6
7    fn try_from(proto: Node) -> Result<Self, Self::Error> {
8        let payload = if proto.payload.is_empty() {
9            serde_json::Value::Null
10        } else {
11            serde_json::from_slice(&proto.payload).map_err(|e| {
12                VecGraphError::SerializationError(format!("invalid node payload: {}", e))
13            })?
14        };
15
16        Ok(vecgraph_core::Node {
17            id: vecgraph_core::NodeId::try_new(proto.id)?,
18            kind: proto.kind,
19            name: proto.name,
20            namespace: proto.namespace,
21            payload,
22        })
23    }
24}
25
26impl TryFrom<vecgraph_core::Node> for Node {
27    type Error = VecGraphError;
28
29    fn try_from(core: vecgraph_core::Node) -> Result<Self, Self::Error> {
30        let payload = serde_json::to_vec(&core.payload).map_err(|e| {
31            VecGraphError::SerializationError(format!("failed to serialize payload: {}", e))
32        })?;
33
34        Ok(Node {
35            id: core.id.0,
36            kind: core.kind,
37            name: core.name,
38            namespace: core.namespace,
39            payload,
40        })
41    }
42}
43
44impl TryFrom<NodeWithVector> for vecgraph_core::NodeWithVector {
45    type Error = VecGraphError;
46
47    fn try_from(proto: NodeWithVector) -> Result<Self, Self::Error> {
48        let node = proto
49            .node
50            .ok_or_else(|| VecGraphError::Other("NodeWithVector missing node field".into()))?;
51
52        Ok(vecgraph_core::NodeWithVector {
53            node: node.try_into()?,
54            vector: proto.vectors,
55        })
56    }
57}
58
59impl TryFrom<vecgraph_core::NodeWithVector> for NodeWithVector {
60    type Error = VecGraphError;
61
62    fn try_from(core: vecgraph_core::NodeWithVector) -> Result<Self, Self::Error> {
63        Ok(NodeWithVector {
64            node: Some(core.node.try_into()?),
65            vectors: core.vector,
66        })
67    }
68}