use serde::{Deserialize, Deserializer};
use serde_json::value::RawValue;
pub(crate) fn is_default<T: Default + PartialEq>(v: &T) -> bool {
*v == T::default()
}
pub(crate) trait Empty {
fn is_empty(&self) -> bool;
}
#[allow(clippy::ref_option)] pub(crate) fn absent<T: Empty>(v: &Option<T>) -> bool {
v.as_ref().is_none_or(Empty::is_empty)
}
pub(crate) fn nullable<'de, D, T>(d: D) -> Result<T, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de> + Default,
{
Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
}
pub(crate) fn payload<'de, D>(d: D) -> Result<Option<Box<RawValue>>, D::Error>
where
D: Deserializer<'de>,
{
Box::<RawValue>::deserialize(d).map(Some)
}
pub(crate) mod wrapped {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
struct Wrapper<T> {
#[serde(default)]
value: T,
}
#[allow(clippy::ref_option)] pub(crate) fn serialize<T: Serialize + Copy, S: Serializer>(
v: &Option<T>,
s: S,
) -> Result<S::Ok, S::Error> {
match v {
Some(value) => Wrapper { value: *value }.serialize(s),
None => s.serialize_none(),
}
}
pub(crate) fn deserialize<'de, T, D>(d: D) -> Result<Option<T>, D::Error>
where
T: Deserialize<'de> + Default,
D: Deserializer<'de>,
{
Ok(Option::<Wrapper<T>>::deserialize(d)?.map(|w| w.value))
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use crate::{
DeviceLocaleUpdate, DeviceMetaUpdate, DeviceTimezoneUpdate, DeviceUpdateRequest,
DeviceUserUpdate, FilterNode, SubscribeOptionOverride, SubscribeRequest,
};
#[test]
fn zero_values_are_not_sent() {
let req = SubscribeRequest::new("chat").user("42");
let json = serde_json::to_string(&req).unwrap();
assert_eq!(json, r#"{"channel":"chat","user":"42"}"#);
}
#[test]
fn wrappers_are_tri_state() {
let o = SubscribeOptionOverride::new()
.presence(true)
.join_leave(false);
let json = serde_json::to_string(&o).unwrap();
assert_eq!(
json,
r#"{"presence":{"value":true},"join_leave":{"value":false}}"#
);
let back: SubscribeOptionOverride = serde_json::from_str(&json).unwrap();
assert_eq!(back.presence, Some(true));
assert_eq!(back.join_leave, Some(false));
assert_eq!(back.force_recovery, None);
}
#[test]
fn empty_presence_wrappers_are_sent() {
let req = DeviceUpdateRequest::new()
.users(["42"])
.user_update(DeviceUserUpdate::new(""))
.timezone_update(DeviceTimezoneUpdate::new(""))
.locale_update(DeviceLocaleUpdate::new(""))
.meta_update(DeviceMetaUpdate::new(BTreeMap::<String, String>::new()));
let json = serde_json::to_string(&req).unwrap();
assert_eq!(
json,
r#"{"users":["42"],"user_update":{},"meta_update":{},"timezone_update":{},"locale_update":{}}"#
);
let unset = serde_json::to_string(&DeviceUpdateRequest::new().users(["42"])).unwrap();
assert_eq!(unset, r#"{"users":["42"]}"#);
}
#[test]
fn empty_messages_are_not_sent() {
use crate::{
FcmPushNotification, PushLimitStrategy, PushNotification, PushRateLimitStrategy,
PushRecipient, RateLimitPolicy, SendPushNotificationRequest,
};
let push = || {
SendPushNotificationRequest::new(
PushRecipient::new().fcm_tokens(["d"]),
PushNotification::new().fcm(FcmPushNotification::new(
super::RawValue::from_string("{}".into()).unwrap(),
)),
)
};
let want = r#"{"recipient":{"fcm_tokens":["d"]},"notification":{"fcm":{"message":{}}}}"#;
for empty in [
PushLimitStrategy::new(),
PushLimitStrategy::new().rate_limit(PushRateLimitStrategy::new()),
] {
let json = serde_json::to_string(&push().limit_strategy(empty)).unwrap();
assert_eq!(json, want);
}
let json =
serde_json::to_string(&push().limit_strategy(PushLimitStrategy::new().rate_limit(
PushRateLimitStrategy::new().policies([RateLimitPolicy::new(1, 1000)]),
)))
.unwrap();
assert!(
json.ends_with(
r#""limit_strategy":{"rate_limit":{"policies":[{"rate":1,"interval_ms":1000}]}}}"#
),
"{json}"
);
let req = DeviceUpdateRequest::new().user_update(DeviceUserUpdate::new(""));
assert_eq!(
serde_json::to_string(&req).unwrap(),
r#"{"user_update":{}}"#
);
}
#[test]
fn constants_are_their_values() {
use crate::proxy;
let api = [
(crate::FILTER_NODE_OP_AND, "and"),
(crate::FILTER_NODE_OP_OR, "or"),
(crate::FILTER_NODE_OP_NOT, "not"),
(crate::OP_ADD, "add"),
(crate::OP_REMOVE, "remove"),
(crate::OP_SET, "set"),
(crate::CMP_EQ, "eq"),
(crate::CMP_NEQ, "neq"),
(crate::CMP_IN, "in"),
(crate::CMP_NIN, "nin"),
(crate::CMP_EX, "ex"),
(crate::CMP_NEX, "nex"),
(crate::CMP_SW, "sw"),
(crate::CMP_EW, "ew"),
(crate::CMP_CT, "ct"),
(crate::CMP_GT, "gt"),
(crate::CMP_GTE, "gte"),
(crate::CMP_LT, "lt"),
(crate::CMP_LTE, "lte"),
(crate::PROVIDER_FCM, "fcm"),
(crate::PROVIDER_HMS, "hms"),
(crate::PROVIDER_APNS, "apns"),
(crate::PROVIDER_WEBPUSH, "webpush"),
(crate::PLATFORM_IOS, "ios"),
(crate::PLATFORM_ANDROID, "android"),
(crate::PLATFORM_WEB, "web"),
(crate::STATUS_DELIVERED, "delivered"),
(crate::STATUS_INTERACTED, "interacted"),
(crate::KEY_MODE_IF_NEW, "if_new"),
(crate::KEY_MODE_IF_EXISTS, "if_exists"),
];
let proxy = [
(proxy::FILTER_NODE_OP_AND, "and"),
(proxy::FILTER_NODE_OP_OR, "or"),
(proxy::FILTER_NODE_OP_NOT, "not"),
(proxy::CMP_EQ, "eq"),
(proxy::CMP_LTE, "lte"),
(proxy::PROTOCOL_JSON, "json"),
(proxy::PROTOCOL_PROTOBUF, "protobuf"),
(proxy::ENCODING_JSON, "json"),
(proxy::ENCODING_BINARY, "binary"),
(proxy::ALLOW_SUB, "sub"),
(proxy::ALLOW_PUB, "pub"),
(proxy::ALLOW_HST, "hst"),
(proxy::ALLOW_PRS, "prs"),
(proxy::CAPABILITY_MATCH_WILDCARD, "wildcard"),
(proxy::CAPABILITY_MATCH_REGEX, "regex"),
(proxy::KEY_MODE_IF_NEW, "if_new"),
(proxy::KEY_MODE_IF_EXISTS, "if_exists"),
(proxy::CHANNEL_EVENT_TYPE_OCCUPIED, "occupied"),
(proxy::CHANNEL_EVENT_TYPE_VACATED, "vacated"),
];
for (constant, value) in api.into_iter().chain(proxy) {
assert_eq!(constant, value);
}
}
#[test]
fn a_value_without_a_constant_is_sent() {
let req = crate::DeviceRegisterRequest::new("fcm_v2", "x", crate::PLATFORM_IOS);
let json = serde_json::to_string(&req).unwrap();
assert_eq!(
json,
r#"{"provider":"fcm_v2","token":"x","platform":"ios"}"#
);
}
#[test]
fn null_reads_as_zero() {
let f: FilterNode =
serde_json::from_str(r#"{"op":null,"vals":null,"nodes":null}"#).unwrap();
assert!(f.op.is_empty() && f.vals.is_empty() && f.nodes.is_empty());
}
}