1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use serde::{Deserialize, Serialize};
use std::{env, fs, path::Path};

/// Database struct (does not use `::new` instead uses `::init`)
///
/// # Examples
/// ```
/// let db = JsonDB::init("your db name")?;
/// ```
///
/// ### Note:
/// Does not handle errors in version "0.1.0" just passes on to user
///
pub struct JsonDB {
    path: String,
}

impl JsonDB {
    /// Init function (takes the place of `::new`)
    ///
    /// # Examples
    /// ```
    /// let db = JsonDB::init("your db name")?;
    /// ```
    ///
    pub fn init(path: &str) -> Result<JsonDB, Box<dyn std::error::Error>> {
        let db_path = format!("{}/.JsonDB/{}/", env::var("HOME")?, path);
        if !Path::new(&*format!("{}/.JsonDB/{}/", env::var("HOME")?, path)).is_dir() {
            fs::create_dir_all(format!("{}/.JsonDB/{}/", env::var("HOME")?, path))?;
        }
        Ok(JsonDB { path: db_path })
    }

    /// Creates a new collection either in your database or in another collection
    ///
    /// # Examples
    /// ```
    /// db.create_collection("your collection path")?;
    /// ```
    ///
    pub fn create_collection<S>(
        self,
        collection_path: S,
    ) -> Result<JsonDB, Box<dyn std::error::Error>>
    where
        S: Into<String>,
    {
        fs::create_dir(format!("{}/{}", self.path, collection_path.into()))?;
        Ok(self)
    }

    /// Writes (or rewrites) data to document in collection
    ///
    /// # Examples
    /// ```
    /// db.write("your collection path", "your document", "struct that derives serde::serialize")?;
    /// ```
    ///
    pub fn write<J, S>(
        self,
        collection_path: S,
        document: S,
        data: J,
    ) -> Result<JsonDB, Box<dyn std::error::Error>>
    where
        J: Serialize,
        S: Into<String>,
    {
        let serialized = serde_json::to_string(&data)?;
        fs::write(
            format!(
                "{}/{}/{}.data.json",
                self.path,
                collection_path.into(),
                document.into()
            ),
            serialized,
        )?;
        Ok(self)
    }

    /// Reads data from document in collection
    ///
    /// ```
    /// let data: impl serde::Deserialize = db.read("your collection path", "your document")?;
    /// ```
    ///
    pub fn read<D, S>(
        self,
        collection_path: S,
        document: S,
    ) -> Result<D, Box<dyn std::error::Error>>
    where
        for<'a> D: Deserialize<'a>,
        S: Into<String>,
    {
        //let data = serde_json::from_str::<D>(serialized)?;
        let data = serde_json::from_str::<D>(
            fs::read_to_string(format!(
                "{}/{}/{}.data.json",
                self.path,
                collection_path.into(),
                document.into()
            ))?
            .as_str(),
        )?;
        Ok(data)
    }

    /// Deletes document in collection
    ///
    /// # Examples
    /// ```
    /// db.delete("your collection path", "your document")?;
    /// ```
    ///
    pub fn delete<S>(
        self,
        collection_path: S,
        document: S,
    ) -> Result<JsonDB, Box<dyn std::error::Error>>
    where
        S: Into<String>,
    {
        fs::remove_file(format!(
            "{}/{}/{}.data.json",
            self.path,
            collection_path.into(),
            document.into()
        ))?;
        Ok(self)
    }
}