Skip to content

Commit 0be1a87

Browse files
committed
feat: added function that turns protojson into json
1 parent 5b42dde commit 0be1a87

1 file changed

Lines changed: 34 additions & 2 deletions

File tree

adapter/rest/src/main.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use hyper::{
1414
server::conn::http1,
1515
};
1616
use hyper_util::rt::TokioIo;
17+
use serde_json::{Map, Number, Value as J};
1718
use std::collections::HashMap;
1819
use std::convert::Infallible;
1920
use std::net::SocketAddr;
@@ -58,6 +59,36 @@ fn json_error(status: StatusCode, msg: &str) -> Response<Full<Bytes>> {
5859
.unwrap()
5960
}
6061

62+
fn pb_value_to_json(v: &Value) -> serde_json::Value {
63+
match v.kind.as_ref() {
64+
None => J::Null,
65+
66+
Some(Kind::NullValue(_)) => J::Null,
67+
68+
Some(Kind::BoolValue(b)) => J::Bool(*b),
69+
70+
Some(Kind::StringValue(s)) => J::String(s.clone()),
71+
72+
Some(Kind::NumberValue(n)) => {
73+
if let Some(num) = Number::from_f64(*n) {
74+
J::Number(num)
75+
} else {
76+
J::Null
77+
}
78+
}
79+
80+
Some(Kind::ListValue(lv)) => J::Array(lv.values.iter().map(pb_value_to_json).collect()),
81+
82+
Some(Kind::StructValue(st)) => {
83+
let mut obj = Map::new();
84+
for (k, v) in &st.fields {
85+
obj.insert(k.clone(), pb_value_to_json(v));
86+
}
87+
J::Object(obj)
88+
}
89+
}
90+
}
91+
6192
fn build_response(
6293
status: StatusCode,
6394
headers: HashMap<String, String>,
@@ -210,8 +241,9 @@ async fn execute_flow_to_hyper_response(
210241
};
211242

212243
// payload -> json bytes
213-
let json = serde_json::to_vec_pretty(payload_val).unwrap_or_else(|err| {
214-
format!(r#"{{"error":"Serialization failed: {}"}}"#, err).into_bytes()
244+
let json_val = pb_value_to_json(payload_val);
245+
let json = serde_json::to_vec_pretty(&json_val).unwrap_or_else(|err| {
246+
format!(r#"{{"error":"Serialization failed: {:?}"}}"#, err).into_bytes()
215247
});
216248

217249
let status =

0 commit comments

Comments
 (0)