bybit_rust_api/rest/
api_key_pair.rs1use serde::Deserialize;
2use std::collections::HashMap;
3use std::fs::File;
4use std::io::{BufReader, Read};
5
6#[derive(Debug, Clone, Deserialize)]
7pub struct ApiKeyPair {
8 profile_name: String,
9 key: String,
10 secret: String,
11}
12
13#[derive(Debug, Deserialize)]
14pub struct ApiKeyPairs {
15 #[serde(rename = "profiles")]
16 pairs: HashMap<String, ApiKeyPair>,
17}
18
19impl ApiKeyPair {
20 pub fn new(profile_name: String, key: String, secret: String) -> ApiKeyPair {
21 ApiKeyPair {
22 profile_name: profile_name.to_string(),
23 key: key.to_string(),
24 secret: secret.to_string(),
25 }
26 }
27
28 pub fn profile_name(&self) -> &str {
29 self.profile_name.as_str()
30 }
31
32 pub fn key(&self) -> &str {
33 self.key.as_str()
34 }
35
36 pub fn secret(&self) -> &str {
37 self.secret.as_str()
38 }
39}
40
41impl ApiKeyPairs {
42 pub fn new() -> ApiKeyPairs {
43 ApiKeyPairs {
44 pairs: HashMap::new(),
45 }
46 }
47
48 pub fn add(&mut self, profile_name: String, key: String, secret: String) {
49 self.pairs.insert(
50 profile_name.to_string(),
51 ApiKeyPair::new(profile_name, key, secret),
52 );
53 }
54
55 pub fn get(&self, profile_name: &str) -> Option<&ApiKeyPair> {
56 self.pairs.get(profile_name)
57 }
58
59 pub fn load_from_json_file(file_path: &str) -> Result<ApiKeyPairs, Box<dyn std::error::Error>> {
74 let mut api_key_pairs = ApiKeyPairs::new();
75 let pairs: Vec<ApiKeyPair> =
76 serde_json::from_reader(BufReader::new(File::open(file_path)?))?;
77 for pair in pairs {
78 api_key_pairs.add(pair.profile_name, pair.key, pair.secret);
79 }
80 Ok(api_key_pairs)
81 }
82
83 pub fn load_from_yaml_file(file_path: &str) -> Result<ApiKeyPairs, Box<dyn std::error::Error>> {
94 let mut file = File::open(file_path).expect(&format!("Unable to open file: {}", file_path));
95 let mut contents = String::new();
96 file.read_to_string(&mut contents)
97 .expect(&format!("Unable to read file: {}", file_path));
98 let pairs: ApiKeyPairs =
99 serde_yaml::from_str(&contents).expect(&format!("Unable to parse file: {}", file_path));
100
101 Ok(pairs)
102 }
103}