Skip to main content

y_sweet/stores/
filesystem.rs

1use async_trait::async_trait;
2use std::{
3    fs::{create_dir_all, remove_file},
4    path::PathBuf,
5};
6use y_sweet_core::store::{Result, Store, StoreError};
7
8pub struct FileSystemStore {
9    base_path: PathBuf,
10}
11
12impl FileSystemStore {
13    pub fn new(base_path: PathBuf) -> std::result::Result<Self, std::io::Error> {
14        create_dir_all(base_path.clone())?;
15        Ok(Self { base_path })
16    }
17}
18
19#[async_trait]
20impl Store for FileSystemStore {
21    async fn init(&self) -> Result<()> {
22        Ok(())
23    }
24
25    async fn get(&self, key: &str) -> Result<Option<Vec<u8>>> {
26        let path = self.base_path.join(key);
27        let contents = std::fs::read(path);
28        match contents {
29            Ok(contents) => Ok(Some(contents)),
30            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
31            Err(e) => Err(StoreError::ConnectionError(e.to_string())),
32        }
33    }
34
35    async fn set(&self, key: &str, value: Vec<u8>) -> Result<()> {
36        let path = self.base_path.join(key);
37        create_dir_all(path.parent().expect("Bad parent"))
38            .map_err(|_| StoreError::NotAuthorized("Error creating directories".to_string()))?;
39        std::fs::write(path, value)
40            .map_err(|_| StoreError::NotAuthorized("Error writing file.".to_string()))?;
41        Ok(())
42    }
43
44    async fn remove(&self, key: &str) -> Result<()> {
45        let path = self.base_path.join(key);
46        remove_file(path)
47            .map_err(|_| StoreError::NotAuthorized("Error removing file.".to_string()))?;
48        Ok(())
49    }
50
51    async fn exists(&self, key: &str) -> Result<bool> {
52        let path = self.base_path.join(key);
53        Ok(path.exists())
54    }
55}