Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map explicitly null response status message to empty string #210

Merged
merged 2 commits into from
Apr 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
Loading