lisk_api_rust_client/connection/
manager.rs1use std::any::Any;
2use std::collections::hash_map::Values;
3use std::collections::HashMap;
4use Connection;
5
6#[derive(Default)]
7pub struct Manager<'a> {
8 connections: HashMap<String, &'a Any>,
9 default_connection: String,
10}
11
12impl<'a> Manager<'a> {
13 pub fn new() -> Manager<'a> {
14 Manager {
15 connections: HashMap::<String, &'a Any>::new(),
16 default_connection: String::from("main"),
17 }
18 }
19
20 pub fn connect(&mut self, connection: &'a Connection) -> Result<(), &str> {
21 let default_connection = &self.get_default_connection();
22 self.connect_as(connection, default_connection)
23 }
24
25 pub fn connect_as(&mut self, connection: &'a Connection, name: &str) -> Result<(), &str> {
26 if self.connections.contains_key(name) {
27 return Err("Connection instance already exists");
28 }
29
30 self.connections.insert(name.to_owned(), connection);
31 Ok(())
32 }
33
34 pub fn disconnect(&mut self, name: &str) {
35 if name.is_empty() {
36 self.connections.remove(&self.default_connection);
37 } else {
38 self.connections.remove(name);
39 }
40 }
41
42 pub fn connection(&self) -> Option<&'a Connection> {
43 let connection_name = self.get_default_connection();
44 if let Some(conn) = self.connections.get(&connection_name) {
45 return conn.downcast_ref();
46 }
47
48 None
49 }
50
51 pub fn connection_by_name(&self, name: &str) -> Option<&'a Connection> {
52 if let Some(conn) = self.connections.get(name) {
53 return conn.downcast_ref();
54 }
55
56 None
57 }
58
59 pub fn get_default_connection(&self) -> String {
60 self.default_connection.to_owned()
61 }
62
63 pub fn set_default_connection(&mut self, name: &str) {
64 self.default_connection = name.to_owned();
65 }
66
67 pub fn connections(&self) -> Values<String, &'a Any> {
68 self.connections.values()
69 }
70}