Skip to content

Commit

Permalink
Map explicitly null response status message to empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
criminosis committed Apr 19, 2024
1 parent 00cf794 commit cc2728f
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion gremlin-client/src/message.rs
@@ -1,3 +1,4 @@
use serde::{Deserialize, Deserializer};
use serde_derive::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
Expand Down Expand Up @@ -65,10 +66,18 @@ pub struct ResponseResult {
pub struct ReponseStatus {
pub code: i16,
//Sometimes the message is omitted, default to empty string rather than panic
#[serde(default)]
#[serde(default, deserialize_with = "map_null_to_default")]
pub message: String,
}

fn map_null_to_default<'de, D, T>(de: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Default + Deserialize<'de>,
{
Option::<T>::deserialize(de).map(Option::unwrap_or_default)
}

pub fn message_with_args_v2<T>(op: String, processor: String, args: T) -> Message<T> {
message_with_args_and_uuid_v2(op, processor, Uuid::new_v4(), args)
}
Expand Down Expand Up @@ -107,3 +116,33 @@ pub fn message_with_args_and_uuid<T>(
args,
}
}

#[cfg(test)]
mod tests {
use crate::message::ReponseStatus;

#[test]
fn handle_no_response_status_message() {
let parsed: ReponseStatus =
serde_json::from_str(r#"{"code": 123}"#).expect("Failed to parse test message");
assert_eq!(123, parsed.code);
assert_eq!("", parsed.message);
}

#[test]
fn handle_null_response_status_message() {
let parsed: ReponseStatus = serde_json::from_str(r#"{"code": 123, "message": null}"#)
.expect("Failed to parse test message");
assert_eq!(123, parsed.code);
assert_eq!("", parsed.message);
}

#[test]
fn handle_response_status_message() {
let parsed: ReponseStatus =
serde_json::from_str(r#"{"code": 123, "message": "Hello World"}"#)
.expect("Failed to parse test message");
assert_eq!(123, parsed.code);
assert_eq!("Hello World", parsed.message);
}
}

0 comments on commit cc2728f

Please sign in to comment.