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
#[cfg(test)]
#[path = "./connection_test.rs"]
mod connection_test;
use crate::types::{RedisEmptyResult, RedisError, RedisResult};
use std::option::Option;
pub(crate) struct Connection {
connection: Option<redis::Connection>,
}
fn open_connection(connection: &mut Connection, client: &redis::Client) -> RedisEmptyResult {
let output: RedisEmptyResult;
if !connection.is_connection_open() {
output = match client.get_connection() {
Ok(redis_connection) => {
connection.connection = Some(redis_connection);
Ok(())
}
Err(error) => Err(RedisError::RedisError(error)),
}
} else {
output = Ok(());
}
output
}
impl Connection {
pub(crate) fn is_connection_open(self: &mut Connection) -> bool {
let open;
match self.connection {
Some(ref mut redis_connection) => {
let result: redis::RedisResult<()> = redis::cmd("PING").query(redis_connection);
open = result.is_ok();
}
None => open = false,
}
open
}
pub(crate) fn get_redis_connection(
self: &mut Connection,
client: &redis::Client,
) -> RedisResult<&mut redis::Connection> {
match open_connection(self, client) {
Err(error) => Err(error),
_ => match self.connection {
Some(ref mut redis_connection) => Ok(redis_connection),
None => Err(RedisError::Description("Redis connection not available.")),
},
}
}
}
pub(crate) fn create() -> Connection {
Connection { connection: None }
}