Better message serialization

This commit is contained in:
Gregory Schier
2024-02-09 05:00:48 -08:00
parent 2bd9b436e6
commit ba4d1063e3
7 changed files with 49 additions and 22 deletions

View File

@@ -143,12 +143,14 @@ pub fn message_to_json_schema(
schema.properties = Some(properties);
schema.required = Some(
message
.fields()
.map(|f| f.name().to_string())
.collect::<Vec<_>>(),
);
// All proto 3 fields are optional, so maybe we could
// make this a setting?
// schema.required = Some(
// message
// .fields()
// .map(|f| f.name().to_string())
// .collect::<Vec<_>>(),
// );
schema
}

View File

@@ -1,4 +1,4 @@
use prost_reflect::SerializeOptions;
use prost_reflect::{DynamicMessage, SerializeOptions};
use serde::{Deserialize, Serialize};
mod codec;
@@ -25,3 +25,16 @@ pub struct MethodDefinition {
pub client_streaming: bool,
pub server_streaming: bool,
}
static SERIALIZE_OPTIONS: &'static SerializeOptions = &SerializeOptions::new()
.skip_default_fields(false)
.stringify_64_bit_integers(false);
pub fn serialize_message(msg: &DynamicMessage) -> Result<String, String> {
let mut buf = Vec::new();
let mut se = serde_json::Serializer::pretty(&mut buf);
msg.serialize_with_options(&mut se, SERIALIZE_OPTIONS)
.map_err(|e| e.to_string())?;
let s = String::from_utf8(buf).expect("serde_json to emit valid utf8");
Ok(s)
}

View File

@@ -30,7 +30,7 @@ impl GrpcConnection {
service: &str,
method: &str,
message: &str,
) -> Result<String, String> {
) -> Result<DynamicMessage, String> {
let service = self.pool.get_service_by_name(service).unwrap();
let method = &service.methods().find(|m| m.name() == method).unwrap();
let input_message = method.input();
@@ -47,11 +47,11 @@ impl GrpcConnection {
let codec = DynamicCodec::new(method.clone());
client.ready().await.unwrap();
let resp = client.unary(req, path, codec).await.unwrap();
let msg = resp.into_inner();
let response_json = serde_json::to_string_pretty(&msg).expect("json to string");
Ok(response_json)
Ok(client
.unary(req, path, codec)
.await
.map_err(|e| e.to_string())?
.into_inner())
}
pub async fn streaming(

View File

@@ -45,6 +45,7 @@ pub async fn fill_pool_from_files(paths: Vec<PathBuf>) -> Result<DescriptorPool,
let parent = p.as_path().parent();
if let Some(parent_path) = parent {
cmd.arg("-I").arg(parent_path);
cmd.arg("-I").arg(parent_path.parent().unwrap());
} else {
debug!("ignoring {:?} since it does not exist.", parent)
}