1mod mode;
2
3use json::{JsonValue};
4use crate::mode::mode::Mode;
5use crate::mode::redis::Redis;
6#[derive(Clone)]
7pub struct Cache {
8 mode: Mode,
9 db: i8,
10}
11
12impl Cache {
13 pub fn connect(config: JsonValue) -> Self {
14 if config.is_empty() {
15 return Self {
16 mode: Mode::None,
17 db: 0,
18 };
19 }
20 let connections = config["connections"].clone();
21 let default = config["default"].to_string();
22 let connection = connections[default.clone()].clone();
23 let mode = match connection["mode"].as_str().unwrap() {
24 "redis" => {
25 let dsn = {
26 if connection["userpass"] != "" {
27 format!("redis://:{}@{}:{}/", connection["userpass"], connection["hostname"], connection["hostport"])
28 } else {
29 format!("redis://{}:{}/", connection["hostname"], connection["hostport"])
30 }
31 };
32 Mode::Redis(Redis::connect(dsn.clone()))
33 }
34 _ => {
35 let dsn = {
36 if connection["userpass"] != "" {
37 format!("redis://:{}@{}:{}/", connection["userpass"], connection["hostname"], connection["hostport"])
38 } else {
39 format!("redis://{}:{}/", connection["hostname"], connection["hostport"])
40 }
41 };
42 Mode::Redis(Redis::connect(dsn.clone()))
43 }
44 };
45 Self {
46 mode,
47 db: 0,
48 }
49 }
50 pub fn db(&mut self, db: i8) -> &mut Self {
52 self.db = db;
53 self
54 }
55 pub fn set(&mut self, key: &str, value: JsonValue, time: usize) -> bool {
59 self.mode.set(self.db, key, value, time)
60 }
61 pub fn get(&mut self, key: &str) -> JsonValue {
63 self.mode.get(self.db, key)
64 }
65 pub fn del(&mut self, key: &str) -> bool {
67 self.mode.del(self.db, key)
68 }
69
70 pub fn set_list(&mut self, key: &str, value: JsonValue) -> bool {
72 self.mode.set_list(self.db, key, value)
73 }
74 pub fn get_list(&mut self, key: &str) -> JsonValue {
76 self.mode.get_list(self.db, key)
77 }
78
79 pub fn set_message_queue(&mut self, key: &str, value: JsonValue) -> bool {
81 self.mode.set_message_queue(self.db, key, value)
82 }
83 pub fn get_message_queue(&mut self, key: &str) -> JsonValue {
85 self.mode.get_message_queue(self.db, key)
86 }
87 pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> bool {
88 self.mode.set_object(self.db, key, field, value)
89 }
90 pub fn get_object(&mut self, key: &str) -> JsonValue {
92 self.mode.get_object(self.db, key)
93 }
94}