Skip to content

Commit

Permalink
refactor(satellite): replace std::fs with tokio::fs for asynchronous …
Browse files Browse the repository at this point in the history
…file operations

- Update imports to use tokio::fs instead of std::fs for file operations
- Modify file operations to use asynchronous versions (e.g., fs::write -> fs::write.await)
- Update the code to work with tokio's asynchronous runtime
  • Loading branch information
ShenMian committed Dec 10, 2024
1 parent c7c9550 commit 85969f9
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/satellite.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{fs, time::Duration};
use std::time::Duration;

use strum::{Display, EnumIter};
use tokio::fs;
use ureq::serde_json;

#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Display, EnumIter)]
Expand Down Expand Up @@ -55,18 +56,23 @@ impl Satellite {
let cache_path = dirs::cache_dir()
.expect("failed to get cache directory")
.join(format!("tracker/{}.json", self.to_string().to_lowercase()));
fs::create_dir_all(cache_path.parent().unwrap()).unwrap();
fs::create_dir_all(cache_path.parent().unwrap())
.await
.unwrap();

// Fetch elements if cache doesn't exist
if !fs::exists(&cache_path).unwrap() {
if !std::fs::exists(&cache_path).unwrap() {
if let Some(elements) = self.fetch_elements().await {
fs::write(&cache_path, serde_json::to_string(&elements).unwrap()).unwrap();
fs::write(&cache_path, serde_json::to_string(&elements).unwrap())
.await
.unwrap();
} else {
return None;
}
}

let age = fs::metadata(&cache_path)
.await
.unwrap()
.modified()
.unwrap()
Expand All @@ -77,11 +83,13 @@ impl Satellite {
// Fetch elements if cache is older than 2 hours
if is_cache_expired {
if let Some(elements) = self.fetch_elements().await {
fs::write(&cache_path, serde_json::to_string(&elements).unwrap()).unwrap();
fs::write(&cache_path, serde_json::to_string(&elements).unwrap())
.await
.unwrap();
}
}

let json = fs::read_to_string(&cache_path).unwrap();
let json = fs::read_to_string(&cache_path).await.unwrap();
serde_json::from_str(&json).unwrap()
}

Expand Down

0 comments on commit 85969f9

Please sign in to comment.