From c4ed717aca95116a54f4205a66a9877ca4e9aaae Mon Sep 17 00:00:00 2001 From: tobinio Date: Sun, 29 Mar 2026 12:38:41 +0200 Subject: [PATCH] move fetch code to lib --- Cargo.lock | 6 ++++ notification-daemon/src/main.rs | 61 +-------------------------------- 2 files changed, 7 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5e54983..04de719 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -361,7 +361,13 @@ name = "client" version = "0.1.0" dependencies = [ "chrono", + "color-eyre", + "futures", + "reqwest", + "reqwest-eventsource", "serde", + "serde_json", + "tokio", ] [[package]] diff --git a/notification-daemon/src/main.rs b/notification-daemon/src/main.rs index 4facb1d..be0a5b3 100644 --- a/notification-daemon/src/main.rs +++ b/notification-daemon/src/main.rs @@ -1,10 +1,5 @@ use clap::Parser; -use client::Todo; -use color_eyre::eyre; -use futures::stream::StreamExt; -use reqwest_eventsource::{Event, EventSource}; -use std::{thread, time::Duration}; -use tokio::sync::mpsc::{self, Receiver}; +use client::fetch::get_todos; #[derive(Parser, Debug)] #[command(version, about, long_about = None)] @@ -29,57 +24,3 @@ async fn main() { } } } - -fn get_todos(url: String, token: String) -> Receiver> { - let (tx, rx) = mpsc::channel(8); - - tokio::spawn(async move { - loop { - let todos = loop { - match fetch_todos(&url, &token).await { - Ok(todos) => break todos, - Err(err) => { - eprintln!("Error fetching todos: {}", err); - thread::sleep(Duration::from_secs(5)); - } - } - }; - - tx.send(todos).await.unwrap(); - - let mut event_source = EventSource::new( - reqwest::Client::new() - .get(format!("{}{}", url, "/api/todos/sse")) - .header("Authorization", format!("Bearer {}", token)), - ) - .unwrap(); - while let Some(event) = event_source.next().await { - match event { - Ok(Event::Open) => {} - Ok(Event::Message(message)) => { - let todos = serde_json::from_str(&message.data).unwrap(); - tx.send(todos).await.unwrap(); - } - Err(err) => { - eprintln!("Error: {}", err); - break; - } - } - } - } - }); - - rx -} - -async fn fetch_todos(url: &str, token: &str) -> eyre::Result> { - let response = reqwest::Client::new() - .get(format!("{}{}", url, "/api/todos")) - .header("Authorization", format!("Bearer {}", token)) - .send() - .await? - .text() - .await?; - - Ok(serde_json::from_str(&response)?) -} -- 2.51.2