Skip to content

Instantly share code, notes, and snippets.

@ywegel
Created March 31, 2024 21:34
Show Gist options
  • Save ywegel/18377fc233581b8865ea17a7a5b14f80 to your computer and use it in GitHub Desktop.
Save ywegel/18377fc233581b8865ea17a7a5b14f80 to your computer and use it in GitHub Desktop.
Sending fcm message
// DISCLAIMER: This code is provided as is without any warranties. It's primarily for learning and informational purposes.
// The author does not guarantee that the code is fit for any particular purpose and will not be responsible for any damage or loss resulting from the use of this code.
// The author does not assume liability for the code.
use crate::error::ResponseError;
use anyhow::anyhow;
use serde_json::json;
use crate::config::Config;
use reqwest::Client;
async fn send_push_notification(
device_token: &str,
entity: Entity,
access_token: &str,
project_id: &str,
) -> Result<(), ResponseError> {
let client = Client::new();
let url = format!("https://fcm.googleapis.com/v1/projects/{}/messages:send", project_id);
let entity_data = entity.into_hashmap();
let payload = json!({
"message": {
"token": device_token,
"data": entity_data
}
});
let res = client
.post(&url)
.bearer_auth(access_token)
.json(&payload)
.send()
.await?;
if res.status().is_success() {
Ok(())
} else {
Err(ResponseError::Other(anyhow!("Failed to send push notification: {}", res.text().await?)))
}
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct Entity {
pub your: String,
pub fields: String,
}
impl Entity {
pub fn into_hashmap(self) -> HashMap<String, String> {
let mut map = HashMap::new();
map.insert("your".to_string(), self.your);
map.insert("fields".to_string(), self.fields);
map
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment