Skip to content

Commit

Permalink
Map explicitly null response status message to empty string (#210)
Browse files Browse the repository at this point in the history
* Map explicitly null response status message to empty string

* Disambiguate Deserialize
  • Loading branch information
criminosis authored Apr 24, 2024
1 parent 00cf794 commit a6f5ad8
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion gremlin-client/src/message.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use serde::{Deserialize as SerdeDeserialize, 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 + SerdeDeserialize<'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 a6f5ad8

Please sign in to comment.