Skip to content

Commit

Permalink
Merge pull request #3 from rj76/develop
Browse files Browse the repository at this point in the history
Bugfix in sending message
  • Loading branch information
rj76 authored Jan 5, 2024
2 parents fc708f5 + 8f295b1 commit a8babd2
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 10 deletions.
15 changes: 13 additions & 2 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::Message;
use gauth::serv_account::ServiceAccount;
use reqwest::header::RETRY_AFTER;
use reqwest::{Body, StatusCode};
use serde::Serialize;

/// An async client for sending the notification payload.
pub struct Client {
Expand All @@ -17,6 +18,11 @@ impl Default for Client {
}
}

#[derive(Serialize, Debug)]
pub struct MessageWrapper {
pub message: Message,
}

impl Client {
/// Get a new instance of Client.
pub fn new() -> Client {
Expand Down Expand Up @@ -101,7 +107,8 @@ impl Client {
}

pub async fn send(&self, message: Message) -> Result<FcmResponse, FcmError> {
let payload = serde_json::to_vec(&message).unwrap();
let wrapper = MessageWrapper { message };
let payload = serde_json::to_vec(&wrapper).unwrap();

let project_id = match self.get_project_id() {
Ok(project_id) => project_id,
Expand All @@ -123,6 +130,7 @@ impl Client {
.bearer_auth(auth_token)
.body(Body::from(payload))
.build()?;

let response = self.http_client.execute(request).await?;

let response_status = response.status();
Expand All @@ -144,7 +152,10 @@ impl Client {
}
}
StatusCode::UNAUTHORIZED => Err(FcmError::Unauthorized),
StatusCode::BAD_REQUEST => Err(FcmError::InvalidMessage("Bad Request".to_string())),
StatusCode::BAD_REQUEST => {
let body = response.text().await.unwrap();
Err(FcmError::InvalidMessage(format!("Bad Request ({body}")))
}
status if status.is_server_error() => Err(FcmError::ServerError(retry_after)),
_ => Err(FcmError::InvalidMessage("Unknown Error".to_string())),
}
Expand Down
11 changes: 7 additions & 4 deletions src/message/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::android::AndroidConfig;
use crate::apns::ApnsConfig;
use crate::web::WebpushConfig;
use crate::Notification;
use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};
use serde_json::Value;

Expand All @@ -20,11 +21,13 @@ fn output_target<S>(target: &Target, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = s.serialize_map(Some(1))?;
match target {
Target::Token(token) => s.serialize_newtype_struct("token", token.as_str()),
Target::Topic(topic) => s.serialize_newtype_struct("topic", topic.as_str()),
Target::Condition(condition) => s.serialize_newtype_struct("condition", condition.as_str()),
Target::Token(token) => map.serialize_entry("token", token.as_str())?,
Target::Topic(topic) => map.serialize_entry("topic", topic.as_str())?,
Target::Condition(condition) => map.serialize_entry("condition", condition.as_str())?,
}
map.end()
}

#[derive(Serialize, Debug)]
Expand Down Expand Up @@ -55,7 +58,7 @@ pub struct Message {
fcm_options: Option<FcmOptions>,

// Target to send a message to.
#[serde(serialize_with = "output_target")]
#[serde(flatten, serialize_with = "output_target")]
target: Target,
}

Expand Down
44 changes: 40 additions & 4 deletions src/message/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn should_leave_nones_out_of_the_json() {
let payload = serde_json::to_string(&msg).unwrap();

let expected_payload = json!({
"target": "token"
"token": "token"
})
.to_string();

Expand All @@ -48,15 +48,15 @@ fn should_add_custom_data_to_the_payload() {
"foo": "bar",
"bar": false,
},
"target": "token"
"token": "token"
})
.to_string();

assert_eq!(expected_payload, payload);
}

#[test]
fn should_be_able_to_render_a_full_message_to_json() {
fn should_be_able_to_render_a_full_token_message_to_json() {
let target = Target::Token("token".to_string());
let mut builder = MessageBuilder::new(target);

Expand All @@ -66,7 +66,43 @@ fn should_be_able_to_render_a_full_message_to_json() {

let expected_payload = json!({
"notification": {},
"target": "token",
"token": "token",
})
.to_string();

assert_eq!(expected_payload, payload);
}

#[test]
fn should_be_able_to_render_a_full_topic_message_to_json() {
let target = Target::Topic("my_topic".to_string());
let mut builder = MessageBuilder::new(target);

builder.notification(NotificationBuilder::new().finalize());

let payload = serde_json::to_string(&builder.finalize()).unwrap();

let expected_payload = json!({
"notification": {},
"topic": "my_topic",
})
.to_string();

assert_eq!(expected_payload, payload);
}

#[test]
fn should_be_able_to_render_a_full_condition_message_to_json() {
let target = Target::Condition("my_condition".to_string());
let mut builder = MessageBuilder::new(target);

builder.notification(NotificationBuilder::new().finalize());

let payload = serde_json::to_string(&builder.finalize()).unwrap();

let expected_payload = json!({
"notification": {},
"condition": "my_condition",
})
.to_string();

Expand Down

0 comments on commit a8babd2

Please sign in to comment.