refactor(notif): Use discord_client crate

- Moved code into a new Rust crate `node-notifier`
- Create new crate discord client
- node_notifier use now discord client
This commit is contained in:
2025-07-20 13:28:20 +02:00
parent f625268fca
commit 944d9d663d
8 changed files with 1939 additions and 116 deletions

1741
discord_client/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

12
discord_client/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "discord_client"
version = "0.1.0"
edition = "2024"
[dependencies]
reqwest = { version = "0.12.22", features = ["blocking", "json"] }
serde = "1.0.219"
serde_json = "1.0.140"
[dev-dependencies]
mockito = "1.7.0"

68
discord_client/src/lib.rs Normal file
View File

@@ -0,0 +1,68 @@
pub struct DiscordNotifier {
webhook_url: String,
username: String,
avatar_url: String,
}
impl DiscordNotifier {
pub fn new(webhook_url: String, username: String, avatar_url: String) -> DiscordNotifier {
DiscordNotifier {
webhook_url,
username,
avatar_url,
}
}
pub fn send_notification(&self, message: &str) -> Result<(), Box<dyn std::error::Error>> {
let client = reqwest::blocking::Client::new();
let payload = serde_json::json!({
"content": message,
"username": self.username,
"avatar_url": self.avatar_url
});
client
.post(&self.webhook_url)
.json(&payload)
.send()
.map(|_| ())
.map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
}
}
#[test]
fn test_send_notification() {
use serde_json::json;
const USERNAME: &str = "TEST_USER";
const AVATAR_URL: &str = "https://example.com/avatar.png";
const MESSAGE: &str = "Test message";
let mut server = mockito::Server::new();
let mock = server
.mock("POST", "/")
.with_status(204)
.match_header("content-type", "application/json")
.match_body(mockito::Matcher::Json(json!({
"content": MESSAGE,
"username": USERNAME,
"avatar_url": AVATAR_URL
})))
.create();
let webhook_url = server.url();
let notifier = DiscordNotifier::new(
webhook_url.clone(),
USERNAME.to_string(),
AVATAR_URL.to_string(),
);
let result = notifier.send_notification(MESSAGE);
assert!(
result.is_ok(),
"{}",
format!("Failed to send notification: {:?}", result.err())
);
mock.assert();
}