funpay_client/storage/
json.rs

1use crate::storage::StateStorage;
2use async_trait::async_trait;
3use std::collections::HashMap;
4use std::path::PathBuf;
5use tokio::fs;
6
7pub struct JsonFileStorage {
8    path: PathBuf,
9}
10
11impl JsonFileStorage {
12    pub fn new(path: PathBuf) -> Self {
13        Self { path }
14    }
15}
16
17#[async_trait]
18impl StateStorage for JsonFileStorage {
19    async fn load(&self) -> anyhow::Result<HashMap<i64, i64>> {
20        if !self.path.exists() {
21            return Ok(HashMap::new());
22        }
23        let content = fs::read_to_string(&self.path).await?;
24        let data = serde_json::from_str(&content)?;
25        Ok(data)
26    }
27
28    async fn save(&self, data: &HashMap<i64, i64>) -> anyhow::Result<()> {
29        if let Some(parent) = self.path.parent() {
30            if !parent.as_os_str().is_empty() {
31                fs::create_dir_all(parent).await?;
32            }
33        }
34        let serialized = serde_json::to_string(data)?;
35        fs::write(&self.path, serialized).await?;
36        Ok(())
37    }
38}