summaryrefslogtreecommitdiff
path: root/src/storage.rs
diff options
context:
space:
mode:
authorFxQnLr <[email protected]>2024-04-10 00:16:55 +0200
committerFxQnLr <[email protected]>2024-04-10 00:16:55 +0200
commit3428a637ce420baef9aa9f9803e71bd587867005 (patch)
treea1ad8234ae9bf3709794324a41e38c2f7fa58d0d /src/storage.rs
parent907e5cb5bc48899b444f7fedd85af7b5974d9a2e (diff)
downloadwebol-3428a637ce420baef9aa9f9803e71bd587867005.tar
webol-3428a637ce420baef9aa9f9803e71bd587867005.tar.gz
webol-3428a637ce420baef9aa9f9803e71bd587867005.zip
Closes #24. Changed postgres to json directory storage
Diffstat (limited to 'src/storage.rs')
-rw-r--r--src/storage.rs65
1 files changed, 65 insertions, 0 deletions
diff --git a/src/storage.rs b/src/storage.rs
new file mode 100644
index 0000000..6ba5ee1
--- /dev/null
+++ b/src/storage.rs
@@ -0,0 +1,65 @@
1use std::{
2 fs::{create_dir_all, File},
3 io::{Read, Write},
4 path::Path,
5};
6
7use ipnetwork::IpNetwork;
8use mac_address::MacAddress;
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use tracing::{debug, warn};
12use utoipa::ToSchema;
13
14use crate::error::Error;
15
16#[derive(Serialize, Deserialize, Clone, Debug)]
17pub struct Device {
18 pub id: String,
19 pub mac: MacAddress,
20 pub broadcast_addr: String,
21 pub ip: IpNetwork,
22 pub times: Option<Vec<i64>>,
23}
24
25impl Device {
26 const STORAGE_PATH: &'static str = "devices";
27
28 pub fn setup() -> Result<String, Error> {
29 let sp = Path::new(Self::STORAGE_PATH);
30 if !sp.exists() {
31 warn!("device storage path doesn't exist, creating it");
32 create_dir_all(Self::STORAGE_PATH)?;
33 };
34
35 debug!("device storage at '{}'", Self::STORAGE_PATH);
36
37 Ok(Self::STORAGE_PATH.to_string())
38 }
39
40 pub fn read(id: &str) -> Result<Self, Error> {
41 let mut file = File::open(format!("{}/{id}.json", Self::STORAGE_PATH))?;
42 let mut buf = String::new();
43 file.read_to_string(&mut buf)?;
44
45 let dev = serde_json::from_str(&buf)?;
46 Ok(dev)
47 }
48
49 pub fn write(&self) -> Result<(), Error> {
50 let mut file = File::create(format!("{}/{}.json", Self::STORAGE_PATH, self.id))?;
51 file.write_all(json!(self).to_string().as_bytes())?;
52
53 Ok(())
54 }
55}
56
57#[derive(ToSchema)]
58#[schema(as = Device)]
59pub struct DeviceSchema {
60 pub id: String,
61 pub mac: String,
62 pub broadcast_addr: String,
63 pub ip: String,
64 pub times: Option<Vec<i64>>,
65}