From a6f5ad883ad4ab40922716b463e4c76b7d388c83 Mon Sep 17 00:00:00 2001 From: Allan Clements Date: Wed, 24 Apr 2024 04:39:41 -0500 Subject: [PATCH] Map explicitly null response status message to empty string (#210) * Map explicitly null response status message to empty string * Disambiguate Deserialize --- gremlin-client/src/message.rs | 41 ++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/gremlin-client/src/message.rs b/gremlin-client/src/message.rs index 08309c10..bd2530b3 100644 --- a/gremlin-client/src/message.rs +++ b/gremlin-client/src/message.rs @@ -1,3 +1,4 @@ +use serde::{Deserialize as SerdeDeserialize, Deserializer}; use serde_derive::{Deserialize, Serialize}; use serde_json::Value; use uuid::Uuid; @@ -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 +where + D: Deserializer<'de>, + T: Default + SerdeDeserialize<'de>, +{ + Option::::deserialize(de).map(Option::unwrap_or_default) +} + pub fn message_with_args_v2(op: String, processor: String, args: T) -> Message { message_with_args_and_uuid_v2(op, processor, Uuid::new_v4(), args) } @@ -107,3 +116,33 @@ pub fn message_with_args_and_uuid( 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); + } +}